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.
1042 #[clippy::version = "pre 1.29.0"]
1043 pub SINGLE_CHAR_PATTERN,
1045 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
1048 declare_clippy_lint! {
1049 /// ### What it does
1050 /// Checks for calling `.step_by(0)` on iterators which panics.
1052 /// ### Why is this bad?
1053 /// This very much looks like an oversight. Use `panic!()` instead if you
1054 /// actually intend to panic.
1057 /// ```rust,should_panic
1058 /// for x in (0..100).step_by(0) {
1062 #[clippy::version = "pre 1.29.0"]
1063 pub ITERATOR_STEP_BY_ZERO,
1065 "using `Iterator::step_by(0)`, which will panic at runtime"
1068 declare_clippy_lint! {
1069 /// ### What it does
1070 /// Checks for indirect collection of populated `Option`
1072 /// ### Why is this bad?
1073 /// `Option` is like a collection of 0-1 things, so `flatten`
1074 /// automatically does this without suspicious-looking `unwrap` calls.
1078 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
1082 /// let _ = std::iter::empty::<Option<i32>>().flatten();
1084 #[clippy::version = "1.53.0"]
1085 pub OPTION_FILTER_MAP,
1087 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
1090 declare_clippy_lint! {
1091 /// ### What it does
1092 /// Checks for the use of `iter.nth(0)`.
1094 /// ### Why is this bad?
1095 /// `iter.next()` is equivalent to
1096 /// `iter.nth(0)`, as they both consume the next element,
1097 /// but is more readable.
1101 /// # use std::collections::HashSet;
1103 /// # let mut s = HashSet::new();
1105 /// let x = s.iter().nth(0);
1108 /// # let mut s = HashSet::new();
1110 /// let x = s.iter().next();
1112 #[clippy::version = "1.42.0"]
1115 "replace `iter.nth(0)` with `iter.next()`"
1118 declare_clippy_lint! {
1119 /// ### What it does
1120 /// Checks for use of `.iter().nth()` (and the related
1121 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1123 /// ### Why is this bad?
1124 /// `.get()` and `.get_mut()` are more efficient and more
1129 /// let some_vec = vec![0, 1, 2, 3];
1130 /// let bad_vec = some_vec.iter().nth(3);
1131 /// let bad_slice = &some_vec[..].iter().nth(3);
1133 /// The correct use would be:
1135 /// let some_vec = vec![0, 1, 2, 3];
1136 /// let bad_vec = some_vec.get(3);
1137 /// let bad_slice = &some_vec[..].get(3);
1139 #[clippy::version = "pre 1.29.0"]
1142 "using `.iter().nth()` on a standard library type with O(1) element access"
1145 declare_clippy_lint! {
1146 /// ### What it does
1147 /// Checks for use of `.skip(x).next()` on iterators.
1149 /// ### Why is this bad?
1150 /// `.nth(x)` is cleaner
1154 /// let some_vec = vec![0, 1, 2, 3];
1155 /// let bad_vec = some_vec.iter().skip(3).next();
1156 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1158 /// The correct use would be:
1160 /// let some_vec = vec![0, 1, 2, 3];
1161 /// let bad_vec = some_vec.iter().nth(3);
1162 /// let bad_slice = &some_vec[..].iter().nth(3);
1164 #[clippy::version = "pre 1.29.0"]
1167 "using `.skip(x).next()` on an iterator"
1170 declare_clippy_lint! {
1171 /// ### What it does
1172 /// Checks for use of `.drain(..)` on `Vec` and `VecDeque` for iteration.
1174 /// ### Why is this bad?
1175 /// `.into_iter()` is simpler with better performance.
1179 /// # use std::collections::HashSet;
1180 /// let mut foo = vec![0, 1, 2, 3];
1181 /// let bar: HashSet<usize> = foo.drain(..).collect();
1185 /// # use std::collections::HashSet;
1186 /// let foo = vec![0, 1, 2, 3];
1187 /// let bar: HashSet<usize> = foo.into_iter().collect();
1189 #[clippy::version = "1.61.0"]
1190 pub ITER_WITH_DRAIN,
1192 "replace `.drain(..)` with `.into_iter()`"
1195 declare_clippy_lint! {
1196 /// ### What it does
1197 /// Checks for using `x.get(x.len() - 1)` instead of
1200 /// ### Why is this bad?
1201 /// Using `x.last()` is easier to read and has the same
1204 /// Note that using `x[x.len() - 1]` is semantically different from
1205 /// `x.last()`. Indexing into the array will panic on out-of-bounds
1206 /// accesses, while `x.get()` and `x.last()` will return `None`.
1208 /// There is another lint (get_unwrap) that covers the case of using
1209 /// `x.get(index).unwrap()` instead of `x[index]`.
1214 /// let x = vec![2, 3, 5];
1215 /// let last_element = x.get(x.len() - 1);
1218 /// let x = vec![2, 3, 5];
1219 /// let last_element = x.last();
1221 #[clippy::version = "1.37.0"]
1222 pub GET_LAST_WITH_LEN,
1224 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
1227 declare_clippy_lint! {
1228 /// ### What it does
1229 /// Checks for use of `.get().unwrap()` (or
1230 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1232 /// ### Why is this bad?
1233 /// Using the Index trait (`[]`) is more clear and more
1236 /// ### Known problems
1237 /// Not a replacement for error handling: Using either
1238 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1239 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1240 /// temporary placeholder for dealing with the `Option` type, then this does
1241 /// not mitigate the need for error handling. If there is a chance that `.get()`
1242 /// will be `None` in your program, then it is advisable that the `None` case
1243 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1248 /// let mut some_vec = vec![0, 1, 2, 3];
1249 /// let last = some_vec.get(3).unwrap();
1250 /// *some_vec.get_mut(0).unwrap() = 1;
1252 /// The correct use would be:
1254 /// let mut some_vec = vec![0, 1, 2, 3];
1255 /// let last = some_vec[3];
1256 /// some_vec[0] = 1;
1258 #[clippy::version = "pre 1.29.0"]
1261 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1264 declare_clippy_lint! {
1265 /// ### What it does
1266 /// Checks for occurrences where one vector gets extended instead of append
1268 /// ### Why is this bad?
1269 /// Using `append` instead of `extend` is more concise and faster
1273 /// let mut a = vec![1, 2, 3];
1274 /// let mut b = vec![4, 5, 6];
1277 /// a.extend(b.drain(..));
1280 /// a.append(&mut b);
1282 #[clippy::version = "1.55.0"]
1283 pub EXTEND_WITH_DRAIN,
1285 "using vec.append(&mut vec) to move the full range of a vector to another"
1288 declare_clippy_lint! {
1289 /// ### What it does
1290 /// Checks for the use of `.extend(s.chars())` where s is a
1291 /// `&str` or `String`.
1293 /// ### Why is this bad?
1294 /// `.push_str(s)` is clearer
1298 /// let abc = "abc";
1299 /// let def = String::from("def");
1300 /// let mut s = String::new();
1301 /// s.extend(abc.chars());
1302 /// s.extend(def.chars());
1304 /// The correct use would be:
1306 /// let abc = "abc";
1307 /// let def = String::from("def");
1308 /// let mut s = String::new();
1309 /// s.push_str(abc);
1310 /// s.push_str(&def);
1312 #[clippy::version = "pre 1.29.0"]
1313 pub STRING_EXTEND_CHARS,
1315 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1318 declare_clippy_lint! {
1319 /// ### What it does
1320 /// Checks for the use of `.cloned().collect()` on slice to
1323 /// ### Why is this bad?
1324 /// `.to_vec()` is clearer
1328 /// let s = [1, 2, 3, 4, 5];
1329 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1331 /// The better use would be:
1333 /// let s = [1, 2, 3, 4, 5];
1334 /// let s2: Vec<isize> = s.to_vec();
1336 #[clippy::version = "pre 1.29.0"]
1337 pub ITER_CLONED_COLLECT,
1339 "using `.cloned().collect()` on slice to create a `Vec`"
1342 declare_clippy_lint! {
1343 /// ### What it does
1344 /// Checks for usage of `_.chars().last()` or
1345 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1347 /// ### Why is this bad?
1348 /// Readability, this can be written more concisely as
1349 /// `_.ends_with(_)`.
1353 /// # let name = "_";
1356 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1359 /// name.ends_with('_') || name.ends_with('-');
1361 #[clippy::version = "pre 1.29.0"]
1364 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1367 declare_clippy_lint! {
1368 /// ### What it does
1369 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1370 /// types before and after the call are the same.
1372 /// ### Why is this bad?
1373 /// The call is unnecessary.
1377 /// # fn do_stuff(x: &[i32]) {}
1378 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1379 /// do_stuff(x.as_ref());
1381 /// The correct use would be:
1383 /// # fn do_stuff(x: &[i32]) {}
1384 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1387 #[clippy::version = "pre 1.29.0"]
1390 "using `as_ref` where the types before and after the call are the same"
1393 declare_clippy_lint! {
1394 /// ### What it does
1395 /// Checks for using `fold` when a more succinct alternative exists.
1396 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1397 /// `sum` or `product`.
1399 /// ### Why is this bad?
1404 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1406 /// This could be written as:
1408 /// let _ = (0..3).any(|x| x > 2);
1410 #[clippy::version = "pre 1.29.0"]
1411 pub UNNECESSARY_FOLD,
1413 "using `fold` when a more succinct alternative exists"
1416 declare_clippy_lint! {
1417 /// ### What it does
1418 /// Checks for `filter_map` calls that could be replaced by `filter` or `map`.
1419 /// More specifically it checks if the closure provided is only performing one of the
1420 /// filter or map operations and suggests the appropriate option.
1422 /// ### Why is this bad?
1423 /// Complexity. The intent is also clearer if only a single
1424 /// operation is being performed.
1428 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1430 /// // As there is no transformation of the argument this could be written as:
1431 /// let _ = (0..3).filter(|&x| x > 2);
1435 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1437 /// // As there is no conditional check on the argument this could be written as:
1438 /// let _ = (0..4).map(|x| x + 1);
1440 #[clippy::version = "1.31.0"]
1441 pub UNNECESSARY_FILTER_MAP,
1443 "using `filter_map` when a more succinct alternative exists"
1446 declare_clippy_lint! {
1447 /// ### What it does
1448 /// Checks for `find_map` calls that could be replaced by `find` or `map`. More
1449 /// specifically it checks if the closure provided is only performing one of the
1450 /// find or map operations and suggests the appropriate option.
1452 /// ### Why is this bad?
1453 /// Complexity. The intent is also clearer if only a single
1454 /// operation is being performed.
1458 /// let _ = (0..3).find_map(|x| if x > 2 { Some(x) } else { None });
1460 /// // As there is no transformation of the argument this could be written as:
1461 /// let _ = (0..3).find(|&x| x > 2);
1465 /// let _ = (0..4).find_map(|x| Some(x + 1));
1467 /// // As there is no conditional check on the argument this could be written as:
1468 /// let _ = (0..4).map(|x| x + 1).next();
1470 #[clippy::version = "1.61.0"]
1471 pub UNNECESSARY_FIND_MAP,
1473 "using `find_map` when a more succinct alternative exists"
1476 declare_clippy_lint! {
1477 /// ### What it does
1478 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1481 /// ### Why is this bad?
1482 /// Readability. Calling `into_iter` on a reference will not move out its
1483 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1484 /// `iter_mut` directly.
1489 /// let _ = (&vec![3, 4, 5]).into_iter();
1492 /// let _ = (&vec![3, 4, 5]).iter();
1494 #[clippy::version = "1.32.0"]
1495 pub INTO_ITER_ON_REF,
1497 "using `.into_iter()` on a reference"
1500 declare_clippy_lint! {
1501 /// ### What it does
1502 /// Checks for calls to `map` followed by a `count`.
1504 /// ### Why is this bad?
1505 /// It looks suspicious. Maybe `map` was confused with `filter`.
1506 /// If the `map` call is intentional, this should be rewritten
1507 /// using `inspect`. Or, if you intend to drive the iterator to
1508 /// completion, you can just use `for_each` instead.
1512 /// let _ = (0..3).map(|x| x + 2).count();
1514 #[clippy::version = "1.39.0"]
1517 "suspicious usage of map"
1520 declare_clippy_lint! {
1521 /// ### What it does
1522 /// Checks for `MaybeUninit::uninit().assume_init()`.
1524 /// ### Why is this bad?
1525 /// For most types, this is undefined behavior.
1527 /// ### Known problems
1528 /// For now, we accept empty tuples and tuples / arrays
1529 /// of `MaybeUninit`. There may be other types that allow uninitialized
1530 /// data, but those are not yet rigorously defined.
1534 /// // Beware the UB
1535 /// use std::mem::MaybeUninit;
1537 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1540 /// Note that the following is OK:
1543 /// use std::mem::MaybeUninit;
1545 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1546 /// MaybeUninit::uninit().assume_init()
1549 #[clippy::version = "1.39.0"]
1550 pub UNINIT_ASSUMED_INIT,
1552 "`MaybeUninit::uninit().assume_init()`"
1555 declare_clippy_lint! {
1556 /// ### What it does
1557 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1559 /// ### Why is this bad?
1560 /// These can be written simply with `saturating_add/sub` methods.
1564 /// # let y: u32 = 0;
1565 /// # let x: u32 = 100;
1566 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1567 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1570 /// can be written using dedicated methods for saturating addition/subtraction as:
1573 /// # let y: u32 = 0;
1574 /// # let x: u32 = 100;
1575 /// let add = x.saturating_add(y);
1576 /// let sub = x.saturating_sub(y);
1578 #[clippy::version = "1.39.0"]
1579 pub MANUAL_SATURATING_ARITHMETIC,
1581 "`.checked_add/sub(x).unwrap_or(MAX/MIN)`"
1584 declare_clippy_lint! {
1585 /// ### What it does
1586 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1587 /// zero-sized types
1589 /// ### Why is this bad?
1590 /// This is a no-op, and likely unintended
1594 /// unsafe { (&() as *const ()).offset(1) };
1596 #[clippy::version = "1.41.0"]
1599 "Check for offset calculations on raw pointers to zero-sized types"
1602 declare_clippy_lint! {
1603 /// ### What it does
1604 /// Checks for `FileType::is_file()`.
1606 /// ### Why is this bad?
1607 /// When people testing a file type with `FileType::is_file`
1608 /// they are testing whether a path is something they can get bytes from. But
1609 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1610 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1615 /// let metadata = std::fs::metadata("foo.txt")?;
1616 /// let filetype = metadata.file_type();
1618 /// if filetype.is_file() {
1621 /// # Ok::<_, std::io::Error>(())
1625 /// should be written as:
1629 /// let metadata = std::fs::metadata("foo.txt")?;
1630 /// let filetype = metadata.file_type();
1632 /// if !filetype.is_dir() {
1635 /// # Ok::<_, std::io::Error>(())
1638 #[clippy::version = "1.42.0"]
1639 pub FILETYPE_IS_FILE,
1641 "`FileType::is_file` is not recommended to test for readable file type"
1644 declare_clippy_lint! {
1645 /// ### What it does
1646 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1648 /// ### Why is this bad?
1649 /// Readability, this can be written more concisely as
1654 /// # let opt = Some("".to_string());
1655 /// opt.as_ref().map(String::as_str)
1658 /// Can be written as
1660 /// # let opt = Some("".to_string());
1664 #[clippy::version = "1.42.0"]
1665 pub OPTION_AS_REF_DEREF,
1667 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1670 declare_clippy_lint! {
1671 /// ### What it does
1672 /// Checks for usage of `iter().next()` on a Slice or an Array
1674 /// ### Why is this bad?
1675 /// These can be shortened into `.get()`
1679 /// # let a = [1, 2, 3];
1680 /// # let b = vec![1, 2, 3];
1681 /// a[2..].iter().next();
1682 /// b.iter().next();
1684 /// should be written as:
1686 /// # let a = [1, 2, 3];
1687 /// # let b = vec![1, 2, 3];
1691 #[clippy::version = "1.46.0"]
1692 pub ITER_NEXT_SLICE,
1694 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1697 declare_clippy_lint! {
1698 /// ### What it does
1699 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1700 /// where `push`/`insert` with a `char` would work fine.
1702 /// ### Why is this bad?
1703 /// It's less clear that we are pushing a single character.
1707 /// let mut string = String::new();
1708 /// string.insert_str(0, "R");
1709 /// string.push_str("R");
1711 /// Could be written as
1713 /// let mut string = String::new();
1714 /// string.insert(0, 'R');
1715 /// string.push('R');
1717 #[clippy::version = "1.49.0"]
1718 pub SINGLE_CHAR_ADD_STR,
1720 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1723 declare_clippy_lint! {
1724 /// ### What it does
1725 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1726 /// lazily evaluated closures on `Option` and `Result`.
1728 /// This lint suggests changing the following functions, when eager evaluation results in
1730 /// - `unwrap_or_else` to `unwrap_or`
1731 /// - `and_then` to `and`
1732 /// - `or_else` to `or`
1733 /// - `get_or_insert_with` to `get_or_insert`
1734 /// - `ok_or_else` to `ok_or`
1736 /// ### Why is this bad?
1737 /// Using eager evaluation is shorter and simpler in some cases.
1739 /// ### Known problems
1740 /// It is possible, but not recommended for `Deref` and `Index` to have
1741 /// side effects. Eagerly evaluating them can change the semantics of the program.
1745 /// // example code where clippy issues a warning
1746 /// let opt: Option<u32> = None;
1748 /// opt.unwrap_or_else(|| 42);
1752 /// let opt: Option<u32> = None;
1754 /// opt.unwrap_or(42);
1756 #[clippy::version = "1.48.0"]
1757 pub UNNECESSARY_LAZY_EVALUATIONS,
1759 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1762 declare_clippy_lint! {
1763 /// ### What it does
1764 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1766 /// ### Why is this bad?
1767 /// Using `try_for_each` instead is more readable and idiomatic.
1771 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1775 /// (0..3).try_for_each(|t| Err(t));
1777 #[clippy::version = "1.49.0"]
1778 pub MAP_COLLECT_RESULT_UNIT,
1780 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1783 declare_clippy_lint! {
1784 /// ### What it does
1785 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1788 /// ### Why is this bad?
1789 /// It is recommended style to use collect. See
1790 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1794 /// let five_fives = std::iter::repeat(5).take(5);
1796 /// let v = Vec::from_iter(five_fives);
1798 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1802 /// let five_fives = std::iter::repeat(5).take(5);
1804 /// let v: Vec<i32> = five_fives.collect();
1806 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1808 #[clippy::version = "1.49.0"]
1809 pub FROM_ITER_INSTEAD_OF_COLLECT,
1811 "use `.collect()` instead of `::from_iter()`"
1814 declare_clippy_lint! {
1815 /// ### What it does
1816 /// Checks for usage of `inspect().for_each()`.
1818 /// ### Why is this bad?
1819 /// It is the same as performing the computation
1820 /// inside `inspect` at the beginning of the closure in `for_each`.
1824 /// [1,2,3,4,5].iter()
1825 /// .inspect(|&x| println!("inspect the number: {}", x))
1826 /// .for_each(|&x| {
1827 /// assert!(x >= 0);
1830 /// Can be written as
1832 /// [1,2,3,4,5].iter()
1833 /// .for_each(|&x| {
1834 /// println!("inspect the number: {}", x);
1835 /// assert!(x >= 0);
1838 #[clippy::version = "1.51.0"]
1839 pub INSPECT_FOR_EACH,
1841 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1844 declare_clippy_lint! {
1845 /// ### What it does
1846 /// Checks for usage of `filter_map(|x| x)`.
1848 /// ### Why is this bad?
1849 /// Readability, this can be written more concisely by using `flatten`.
1853 /// # let iter = vec![Some(1)].into_iter();
1854 /// iter.filter_map(|x| x);
1858 /// # let iter = vec![Some(1)].into_iter();
1861 #[clippy::version = "1.52.0"]
1862 pub FILTER_MAP_IDENTITY,
1864 "call to `filter_map` where `flatten` is sufficient"
1867 declare_clippy_lint! {
1868 /// ### What it does
1869 /// Checks for instances of `map(f)` where `f` is the identity function.
1871 /// ### Why is this bad?
1872 /// It can be written more concisely without the call to `map`.
1876 /// let x = [1, 2, 3];
1877 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1881 /// let x = [1, 2, 3];
1882 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1884 #[clippy::version = "1.52.0"]
1887 "using iterator.map(|x| x)"
1890 declare_clippy_lint! {
1891 /// ### What it does
1892 /// Checks for the use of `.bytes().nth()`.
1894 /// ### Why is this bad?
1895 /// `.as_bytes().get()` is more efficient and more
1901 /// let _ = "Hello".bytes().nth(3);
1904 /// let _ = "Hello".as_bytes().get(3);
1906 #[clippy::version = "1.52.0"]
1909 "replace `.bytes().nth()` with `.as_bytes().get()`"
1912 declare_clippy_lint! {
1913 /// ### What it does
1914 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1916 /// ### Why is this bad?
1917 /// These methods do the same thing as `_.clone()` but may be confusing as
1918 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1922 /// let a = vec![1, 2, 3];
1923 /// let b = a.to_vec();
1924 /// let c = a.to_owned();
1928 /// let a = vec![1, 2, 3];
1929 /// let b = a.clone();
1930 /// let c = a.clone();
1932 #[clippy::version = "1.52.0"]
1935 "implicitly cloning a value by invoking a function on its dereferenced type"
1938 declare_clippy_lint! {
1939 /// ### What it does
1940 /// Checks for the use of `.iter().count()`.
1942 /// ### Why is this bad?
1943 /// `.len()` is more efficient and more
1949 /// let some_vec = vec![0, 1, 2, 3];
1950 /// let _ = some_vec.iter().count();
1951 /// let _ = &some_vec[..].iter().count();
1954 /// let some_vec = vec![0, 1, 2, 3];
1955 /// let _ = some_vec.len();
1956 /// let _ = &some_vec[..].len();
1958 #[clippy::version = "1.52.0"]
1961 "replace `.iter().count()` with `.len()`"
1964 declare_clippy_lint! {
1965 /// ### What it does
1966 /// Checks for calls to [`splitn`]
1967 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
1968 /// related functions with either zero or one splits.
1970 /// ### Why is this bad?
1971 /// These calls don't actually split the value and are
1972 /// likely to be intended as a different number.
1978 /// for x in s.splitn(1, ":") {
1984 /// for x in s.splitn(2, ":") {
1988 #[clippy::version = "1.54.0"]
1989 pub SUSPICIOUS_SPLITN,
1991 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
1994 declare_clippy_lint! {
1995 /// ### What it does
1996 /// Checks for manual implementations of `str::repeat`
1998 /// ### Why is this bad?
1999 /// These are both harder to read, as well as less performant.
2004 /// let x: String = std::iter::repeat('x').take(10).collect();
2007 /// let x: String = "x".repeat(10);
2009 #[clippy::version = "1.54.0"]
2010 pub MANUAL_STR_REPEAT,
2012 "manual implementation of `str::repeat`"
2015 declare_clippy_lint! {
2016 /// ### What it does
2017 /// Checks for usages of `str::splitn(2, _)`
2019 /// ### Why is this bad?
2020 /// `split_once` is both clearer in intent and slightly more efficient.
2025 /// let s = "key=value=add";
2026 /// let (key, value) = s.splitn(2, '=').next_tuple()?;
2027 /// let value = s.splitn(2, '=').nth(1)?;
2029 /// let mut parts = s.splitn(2, '=');
2030 /// let key = parts.next()?;
2031 /// let value = parts.next()?;
2036 /// let s = "key=value=add";
2037 /// let (key, value) = s.split_once('=')?;
2038 /// let value = s.split_once('=')?.1;
2040 /// let (key, value) = s.split_once('=')?;
2044 /// The multiple statement variant currently only detects `iter.next()?`/`iter.next().unwrap()`
2045 /// in two separate `let` statements that immediately follow the `splitn()`
2046 #[clippy::version = "1.57.0"]
2047 pub MANUAL_SPLIT_ONCE,
2049 "replace `.splitn(2, pat)` with `.split_once(pat)`"
2052 declare_clippy_lint! {
2053 /// ### What it does
2054 /// Checks for usages of `str::splitn` (or `str::rsplitn`) where using `str::split` would be the same.
2055 /// ### Why is this bad?
2056 /// The function `split` is simpler and there is no performance difference in these cases, considering
2057 /// that both functions return a lazy iterator.
2061 /// let str = "key=value=add";
2062 /// let _ = str.splitn(3, '=').next().unwrap();
2067 /// let str = "key=value=add";
2068 /// let _ = str.split('=').next().unwrap();
2070 #[clippy::version = "1.58.0"]
2071 pub NEEDLESS_SPLITN,
2073 "usages of `str::splitn` that can be replaced with `str::split`"
2076 declare_clippy_lint! {
2077 /// ### What it does
2078 /// Checks for unnecessary calls to [`ToOwned::to_owned`](https://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned)
2079 /// and other `to_owned`-like functions.
2081 /// ### Why is this bad?
2082 /// The unnecessary calls result in useless allocations.
2084 /// ### Known problems
2085 /// `unnecessary_to_owned` can falsely trigger if `IntoIterator::into_iter` is applied to an
2086 /// owned copy of a resource and the resource is later used mutably. See
2087 /// [#8148](https://github.com/rust-lang/rust-clippy/issues/8148).
2091 /// let path = std::path::Path::new("x");
2092 /// foo(&path.to_string_lossy().to_string());
2093 /// fn foo(s: &str) {}
2097 /// let path = std::path::Path::new("x");
2098 /// foo(&path.to_string_lossy());
2099 /// fn foo(s: &str) {}
2101 #[clippy::version = "1.58.0"]
2102 pub UNNECESSARY_TO_OWNED,
2104 "unnecessary calls to `to_owned`-like functions"
2107 declare_clippy_lint! {
2108 /// ### What it does
2109 /// Checks for use of `.collect::<Vec<String>>().join("")` on iterators.
2111 /// ### Why is this bad?
2112 /// `.collect::<String>()` is more concise and might be more performant
2116 /// let vector = vec!["hello", "world"];
2117 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<Vec<String>>().join("");
2118 /// println!("{}", output);
2120 /// The correct use would be:
2122 /// let vector = vec!["hello", "world"];
2123 /// let output = vector.iter().map(|item| item.to_uppercase()).collect::<String>();
2124 /// println!("{}", output);
2126 /// ### Known problems
2127 /// While `.collect::<String>()` is sometimes more performant, there are cases where
2128 /// using `.collect::<String>()` over `.collect::<Vec<String>>().join("")`
2129 /// will prevent loop unrolling and will result in a negative performance impact.
2131 /// Additionally, differences have been observed between aarch64 and x86_64 assembly output,
2132 /// with aarch64 tending to producing faster assembly in more cases when using `.collect::<String>()`
2133 #[clippy::version = "1.61.0"]
2134 pub UNNECESSARY_JOIN,
2136 "using `.collect::<Vec<String>>().join(\"\")` on an iterator"
2139 declare_clippy_lint! {
2140 /// ### What it does
2141 /// Checks for no-op uses of `Option::{as_deref, as_deref_mut}`,
2142 /// for example, `Option<&T>::as_deref()` returns the same type.
2144 /// ### Why is this bad?
2145 /// Redundant code and improving readability.
2149 /// let a = Some(&1);
2150 /// let b = a.as_deref(); // goes from Option<&i32> to Option<&i32>
2152 /// Could be written as:
2154 /// let a = Some(&1);
2157 #[clippy::version = "1.57.0"]
2158 pub NEEDLESS_OPTION_AS_DEREF,
2160 "no-op use of `deref` or `deref_mut` method to `Option`."
2163 declare_clippy_lint! {
2164 /// ### What it does
2165 /// Finds usages of [`char::is_digit`]
2166 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_digit) that
2167 /// can be replaced with [`is_ascii_digit`]
2168 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_digit) or
2169 /// [`is_ascii_hexdigit`]
2170 /// (https://doc.rust-lang.org/stable/std/primitive.char.html#method.is_ascii_hexdigit).
2172 /// ### Why is this bad?
2173 /// `is_digit(..)` is slower and requires specifying the radix.
2177 /// let c: char = '6';
2183 /// let c: char = '6';
2184 /// c.is_ascii_digit();
2185 /// c.is_ascii_hexdigit();
2187 #[clippy::version = "1.61.0"]
2188 pub IS_DIGIT_ASCII_RADIX,
2190 "use of `char::is_digit(..)` with literal radix of 10 or 16"
2193 declare_clippy_lint! {
2195 /// ### Why is this bad?
2199 /// let x = Some(3);
2200 /// x.as_ref().take();
2204 /// let x = Some(3);
2207 #[clippy::version = "1.61.0"]
2208 pub NEEDLESS_OPTION_TAKE,
2210 "using `.as_ref().take()` on a temporary value"
2213 declare_clippy_lint! {
2214 /// ### What it does
2215 /// Checks for `replace` statements which have no effect.
2217 /// ### Why is this bad?
2218 /// It's either a mistake or confusing.
2222 /// "1234".replace("12", "12");
2223 /// "1234".replacen("12", "12", 1);
2225 #[clippy::version = "1.62.0"]
2226 pub NO_EFFECT_REPLACE,
2228 "replace with no effect"
2231 pub struct Methods {
2232 avoid_breaking_exported_api: bool,
2233 msrv: Option<RustcVersion>,
2234 allow_expect_in_tests: bool,
2235 allow_unwrap_in_tests: bool,
2241 avoid_breaking_exported_api: bool,
2242 msrv: Option<RustcVersion>,
2243 allow_expect_in_tests: bool,
2244 allow_unwrap_in_tests: bool,
2247 avoid_breaking_exported_api,
2249 allow_expect_in_tests,
2250 allow_unwrap_in_tests,
2255 impl_lint_pass!(Methods => [
2258 SHOULD_IMPLEMENT_TRAIT,
2259 WRONG_SELF_CONVENTION,
2261 UNWRAP_OR_ELSE_DEFAULT,
2263 RESULT_MAP_OR_INTO_OPTION,
2265 BIND_INSTEAD_OF_MAP,
2274 ITER_OVEREAGER_CLONED,
2275 CLONED_INSTEAD_OF_COPIED,
2277 INEFFICIENT_TO_STRING,
2279 SINGLE_CHAR_PATTERN,
2280 SINGLE_CHAR_ADD_STR,
2284 FILTER_MAP_IDENTITY,
2292 ITERATOR_STEP_BY_ZERO,
2301 STRING_EXTEND_CHARS,
2302 ITER_CLONED_COLLECT,
2306 UNNECESSARY_FILTER_MAP,
2307 UNNECESSARY_FIND_MAP,
2310 UNINIT_ASSUMED_INIT,
2311 MANUAL_SATURATING_ARITHMETIC,
2314 OPTION_AS_REF_DEREF,
2315 UNNECESSARY_LAZY_EVALUATIONS,
2316 MAP_COLLECT_RESULT_UNIT,
2317 FROM_ITER_INSTEAD_OF_COLLECT,
2325 UNNECESSARY_TO_OWNED,
2328 NEEDLESS_OPTION_AS_DEREF,
2329 IS_DIGIT_ASCII_RADIX,
2330 NEEDLESS_OPTION_TAKE,
2334 /// Extracts a method call name, args, and `Span` of the method name.
2335 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(&'tcx str, &'tcx [hir::Expr<'tcx>], Span)> {
2336 if let ExprKind::MethodCall(path, args, _) = recv.kind {
2337 if !args.iter().any(|e| e.span.from_expansion()) {
2338 let name = path.ident.name.as_str();
2339 return Some((name, args, path.ident.span));
2345 impl<'tcx> LateLintPass<'tcx> for Methods {
2346 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
2347 if expr.span.from_expansion() {
2351 self.check_methods(cx, expr);
2354 hir::ExprKind::Call(func, args) => {
2355 from_iter_instead_of_collect::check(cx, expr, args, func);
2357 hir::ExprKind::MethodCall(method_call, args, _) => {
2358 let method_span = method_call.ident.span;
2359 or_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2360 expect_fun_call::check(cx, expr, method_span, method_call.ident.as_str(), args);
2361 clone_on_copy::check(cx, expr, method_call.ident.name, args);
2362 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
2363 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
2364 single_char_add_str::check(cx, expr, args);
2365 into_iter_on_ref::check(cx, expr, method_span, method_call.ident.name, args);
2366 single_char_pattern::check(cx, expr, method_call.ident.name, args);
2367 unnecessary_to_owned::check(cx, expr, method_call.ident.name, args, self.msrv);
2369 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
2370 let mut info = BinaryExprInfo {
2374 eq: op.node == hir::BinOpKind::Eq,
2376 lint_binary_expr_with_method_call(cx, &mut info);
2382 #[allow(clippy::too_many_lines)]
2383 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
2384 if in_external_macro(cx.sess(), impl_item.span) {
2387 let name = impl_item.ident.name.as_str();
2388 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
2389 let item = cx.tcx.hir().expect_item(parent);
2390 let self_ty = cx.tcx.type_of(item.def_id);
2392 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
2394 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
2395 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
2397 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
2398 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
2400 let first_arg_ty = method_sig.inputs().iter().next();
2402 // check conventions w.r.t. conversion method names and predicates
2403 if let Some(first_arg_ty) = first_arg_ty;
2406 // if this impl block implements a trait, lint in trait definition instead
2407 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
2408 // check missing trait implementations
2409 for method_config in &TRAIT_METHODS {
2410 if name == method_config.method_name &&
2411 sig.decl.inputs.len() == method_config.param_count &&
2412 method_config.output_type.matches(&sig.decl.output) &&
2413 method_config.self_kind.matches(cx, self_ty, *first_arg_ty) &&
2414 fn_header_equals(method_config.fn_header, sig.header) &&
2415 method_config.lifetime_param_cond(impl_item)
2419 SHOULD_IMPLEMENT_TRAIT,
2422 "method `{}` can be confused for the standard trait method `{}::{}`",
2423 method_config.method_name,
2424 method_config.trait_name,
2425 method_config.method_name
2429 "consider implementing the trait `{}` or choosing a less ambiguous method name",
2430 method_config.trait_name
2437 if sig.decl.implicit_self.has_implicit_self()
2438 && !(self.avoid_breaking_exported_api
2439 && cx.access_levels.is_exported(impl_item.def_id))
2441 wrong_self_convention::check(
2454 // if this impl block implements a trait, lint in trait definition instead
2455 if implements_trait {
2459 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2460 let ret_ty = return_ty(cx, impl_item.hir_id());
2462 // walk the return type and check for Self (this does not check associated types)
2463 if let Some(self_adt) = self_ty.ty_adt_def() {
2464 if contains_adt_constructor(ret_ty, self_adt) {
2467 } else if contains_ty(ret_ty, self_ty) {
2471 // if return type is impl trait, check the associated types
2472 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2473 // one of the associated types must be Self
2474 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2475 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2476 let assoc_ty = match projection_predicate.term {
2477 ty::Term::Ty(ty) => ty,
2478 ty::Term::Const(_c) => continue,
2480 // walk the associated type and check for Self
2481 if let Some(self_adt) = self_ty.ty_adt_def() {
2482 if contains_adt_constructor(assoc_ty, self_adt) {
2485 } else if contains_ty(assoc_ty, self_ty) {
2492 if name == "new" && ret_ty != self_ty {
2497 "methods called `new` usually return `Self`",
2503 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2504 if in_external_macro(cx.tcx.sess, item.span) {
2509 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2510 if sig.decl.implicit_self.has_implicit_self();
2511 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2514 let first_arg_span = first_arg_ty.span;
2515 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2516 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2517 wrong_self_convention::check(
2519 item.ident.name.as_str(),
2530 if item.ident.name == sym::new;
2531 if let TraitItemKind::Fn(_, _) = item.kind;
2532 let ret_ty = return_ty(cx, item.hir_id());
2533 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2534 if !contains_ty(ret_ty, self_ty);
2541 "methods called `new` usually return `Self`",
2547 extract_msrv_attr!(LateContext);
2551 #[allow(clippy::too_many_lines)]
2552 fn check_methods<'tcx>(&self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
2553 if let Some((name, [recv, args @ ..], span)) = method_call(expr) {
2554 match (name, args) {
2555 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2556 zst_offset::check(cx, expr, recv);
2558 ("and_then", [arg]) => {
2559 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2560 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2561 if !biom_option_linted && !biom_result_linted {
2562 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2565 ("as_deref" | "as_deref_mut", []) => {
2566 needless_option_as_deref::check(cx, expr, recv, name);
2568 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2569 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2570 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2571 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, self.msrv),
2572 ("collect", []) => match method_call(recv) {
2573 Some((name @ ("cloned" | "copied"), [recv2], _)) => {
2574 iter_cloned_collect::check(cx, name, expr, recv2);
2576 Some(("map", [m_recv, m_arg], _)) => {
2577 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2579 Some(("take", [take_self_arg, take_arg], _)) => {
2580 if meets_msrv(self.msrv, msrvs::STR_REPEAT) {
2581 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2586 ("count", []) => match method_call(recv) {
2587 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, true, false),
2588 Some((name2 @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2589 iter_count::check(cx, expr, recv2, name2);
2591 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2594 ("drain", [arg]) => {
2595 iter_with_drain::check(cx, expr, recv, span, arg);
2597 ("expect", [_]) => match method_call(recv) {
2598 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2599 Some(("err", [recv], err_span)) => err_expect::check(cx, expr, recv, self.msrv, span, err_span),
2600 _ => expect_used::check(cx, expr, recv, self.allow_expect_in_tests),
2602 ("extend", [arg]) => {
2603 string_extend_chars::check(cx, expr, recv, arg);
2604 extend_with_drain::check(cx, expr, recv, arg);
2606 ("filter_map", [arg]) => {
2607 unnecessary_filter_map::check(cx, expr, arg, name);
2608 filter_map_identity::check(cx, expr, arg, span);
2610 ("find_map", [arg]) => {
2611 unnecessary_filter_map::check(cx, expr, arg, name);
2613 ("flat_map", [arg]) => {
2614 flat_map_identity::check(cx, expr, arg, span);
2615 flat_map_option::check(cx, expr, arg, span);
2617 ("flatten", []) => match method_call(recv) {
2618 Some(("map", [recv, map_arg], map_span)) => map_flatten::check(cx, expr, recv, map_arg, map_span),
2619 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, true),
2622 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2623 ("for_each", [_]) => {
2624 if let Some(("inspect", [_, _], span2)) = method_call(recv) {
2625 inspect_for_each::check(cx, expr, span2);
2628 ("get", [arg]) => get_last_with_len::check(cx, expr, recv, arg),
2629 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2630 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2631 ("is_digit", [radix]) => is_digit_ascii_radix::check(cx, expr, recv, radix, self.msrv),
2632 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2633 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2634 ("join", [join_arg]) => {
2635 if let Some(("collect", _, span)) = method_call(recv) {
2636 unnecessary_join::check(cx, expr, recv, join_arg, span);
2639 ("last", []) | ("skip", [_]) => {
2640 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2641 if let ("cloned", []) = (name2, args2) {
2642 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2646 (name @ ("map" | "map_err"), [m_arg]) => {
2647 if let Some((name, [recv2, args @ ..], span2)) = method_call(recv) {
2648 match (name, args) {
2649 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, self.msrv),
2650 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, self.msrv),
2651 ("filter", [f_arg]) => {
2652 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2654 ("find", [f_arg]) => {
2655 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true);
2660 map_identity::check(cx, expr, recv, m_arg, name, span);
2662 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2664 if let Some((name2, [recv2, args2 @ ..], _)) = method_call(recv) {
2665 match (name2, args2) {
2666 ("cloned", []) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2667 ("filter", [arg]) => filter_next::check(cx, expr, recv2, arg),
2668 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv2, arg, self.msrv),
2669 ("iter", []) => iter_next_slice::check(cx, expr, recv2),
2670 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv2, arg),
2671 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2676 ("nth", [n_arg]) => match method_call(recv) {
2677 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2678 Some(("cloned", [recv2], _)) => iter_overeager_cloned::check(cx, expr, recv, recv2, false, false),
2679 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2680 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2681 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2683 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2684 ("or_else", [arg]) => {
2685 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2686 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2689 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2690 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2691 suspicious_splitn::check(cx, name, expr, recv, count);
2692 str_splitn::check(cx, name, expr, recv, pat_arg, count, self.msrv);
2695 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2696 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2697 suspicious_splitn::check(cx, name, expr, recv, count);
2700 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2701 ("take", [_arg]) => {
2702 if let Some((name2, [recv2, args2 @ ..], _span2)) = method_call(recv) {
2703 if let ("cloned", []) = (name2, args2) {
2704 iter_overeager_cloned::check(cx, expr, recv, recv2, false, false);
2708 ("take", []) => needless_option_take::check(cx, expr, recv),
2709 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2710 implicit_clone::check(cx, name, expr, recv);
2713 match method_call(recv) {
2714 Some(("get", [recv, get_arg], _)) => {
2715 get_unwrap::check(cx, expr, recv, get_arg, false);
2717 Some(("get_mut", [recv, get_arg], _)) => {
2718 get_unwrap::check(cx, expr, recv, get_arg, true);
2720 Some(("or", [recv, or_arg], or_span)) => {
2721 or_then_unwrap::check(cx, expr, recv, or_arg, or_span);
2725 unwrap_used::check(cx, expr, recv, self.allow_unwrap_in_tests);
2727 ("unwrap_or", [u_arg]) => match method_call(recv) {
2728 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2729 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2731 Some(("map", [m_recv, m_arg], span)) => {
2732 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2736 ("unwrap_or_else", [u_arg]) => match method_call(recv) {
2737 Some(("map", [recv, map_arg], _))
2738 if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, self.msrv) => {},
2740 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2741 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2744 ("replace" | "replacen", [arg1, arg2] | [arg1, arg2, _]) => {
2745 no_effect_replace::check(cx, expr, arg1, arg2);
2753 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2754 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call(recv) {
2755 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2759 /// Used for `lint_binary_expr_with_method_call`.
2760 #[derive(Copy, Clone)]
2761 struct BinaryExprInfo<'a> {
2762 expr: &'a hir::Expr<'a>,
2763 chain: &'a hir::Expr<'a>,
2764 other: &'a hir::Expr<'a>,
2768 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2769 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2770 macro_rules! lint_with_both_lhs_and_rhs {
2771 ($func:expr, $cx:expr, $info:ident) => {
2772 if !$func($cx, $info) {
2773 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2774 if $func($cx, $info) {
2781 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2782 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2783 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2784 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2787 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2788 unsafety: hir::Unsafety::Normal,
2789 constness: hir::Constness::NotConst,
2790 asyncness: hir::IsAsync::NotAsync,
2791 abi: rustc_target::spec::abi::Abi::Rust,
2794 struct ShouldImplTraitCase {
2795 trait_name: &'static str,
2796 method_name: &'static str,
2798 fn_header: hir::FnHeader,
2799 // implicit self kind expected (none, self, &self, ...)
2800 self_kind: SelfKind,
2801 // checks against the output type
2802 output_type: OutType,
2803 // certain methods with explicit lifetimes can't implement the equivalent trait method
2804 lint_explicit_lifetime: bool,
2806 impl ShouldImplTraitCase {
2808 trait_name: &'static str,
2809 method_name: &'static str,
2811 fn_header: hir::FnHeader,
2812 self_kind: SelfKind,
2813 output_type: OutType,
2814 lint_explicit_lifetime: bool,
2815 ) -> ShouldImplTraitCase {
2816 ShouldImplTraitCase {
2823 lint_explicit_lifetime,
2827 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2828 self.lint_explicit_lifetime
2829 || !impl_item.generics.params.iter().any(|p| {
2832 hir::GenericParamKind::Lifetime {
2833 kind: hir::LifetimeParamKind::Explicit
2841 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2842 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2843 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2844 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2845 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2846 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2847 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2848 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2849 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2850 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2851 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2852 // FIXME: default doesn't work
2853 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2854 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2855 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2856 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2857 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2858 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2859 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2860 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2861 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2862 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2863 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2864 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2865 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2866 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2867 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2868 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2869 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2870 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2871 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2872 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2875 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
2884 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2885 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2886 if ty == parent_ty {
2888 } else if ty.is_box() {
2889 ty.boxed_ty() == parent_ty
2890 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2891 if let ty::Adt(_, substs) = ty.kind() {
2892 substs.types().next().map_or(false, |t| t == parent_ty)
2901 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2902 if let ty::Ref(_, t, m) = *ty.kind() {
2903 return m == mutability && t == parent_ty;
2906 let trait_path = match mutability {
2907 hir::Mutability::Not => &paths::ASREF_TRAIT,
2908 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2911 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2913 None => return false,
2915 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2918 fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2919 !matches_value(cx, parent_ty, ty)
2920 && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty)
2921 && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty)
2925 Self::Value => matches_value(cx, parent_ty, ty),
2926 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2927 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2928 Self::No => matches_none(cx, parent_ty, ty),
2933 fn description(self) -> &'static str {
2935 Self::Value => "`self` by value",
2936 Self::Ref => "`self` by reference",
2937 Self::RefMut => "`self` by mutable reference",
2938 Self::No => "no `self`",
2943 #[derive(Clone, Copy)]
2952 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2953 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2955 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2956 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2957 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2958 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2959 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2965 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2966 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2967 matches!(path.res, Res::PrimTy(PrimTy::Bool))
2973 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2974 expected.constness == actual.constness
2975 && expected.unsafety == actual.unsafety
2976 && expected.asyncness == actual.asyncness