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;
16 mod filter_map_identity;
19 mod flat_map_identity;
21 mod from_iter_instead_of_collect;
24 mod inefficient_to_string;
27 mod iter_cloned_collect;
33 mod iterator_step_by_zero;
34 mod manual_saturating_arithmetic;
35 mod map_collect_result_unit;
39 mod option_as_ref_deref;
40 mod option_map_or_none;
41 mod option_map_unwrap_or;
44 mod single_char_add_str;
45 mod single_char_insert_string;
46 mod single_char_pattern;
47 mod single_char_push_string;
49 mod string_extend_chars;
51 mod uninit_assumed_init;
52 mod unnecessary_filter_map;
54 mod unnecessary_lazy_eval;
58 mod wrong_self_convention;
61 use bind_instead_of_map::BindInsteadOfMap;
62 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
63 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
64 use clippy_utils::{contains_return, get_trait_def_id, in_macro, iter_input_pats, paths, return_ty};
65 use if_chain::if_chain;
67 use rustc_hir::def::Res;
68 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
69 use rustc_lint::{LateContext, LateLintPass, LintContext};
70 use rustc_middle::lint::in_external_macro;
71 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
72 use rustc_semver::RustcVersion;
73 use rustc_session::{declare_tool_lint, impl_lint_pass};
74 use rustc_span::symbol::SymbolStr;
75 use rustc_span::{sym, Span};
76 use rustc_typeck::hir_ty_to_ty;
78 declare_clippy_lint! {
79 /// **What it does:** Checks for usages of `cloned()` on an `Iterator` or `Option` where
80 /// `copied()` could be used instead.
82 /// **Why is this bad?** `copied()` is better because it guarantees that the type being cloned
83 /// implements `Copy`.
85 /// **Known problems:** None.
90 /// [1, 2, 3].iter().cloned();
94 /// [1, 2, 3].iter().copied();
96 pub CLONED_INSTEAD_OF_COPIED,
98 "used `cloned` where `copied` could be used instead"
101 declare_clippy_lint! {
102 /// **What it does:** Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
105 /// **Why is this bad?** When applicable, `filter_map()` is more clear since it shows that
106 /// `Option` is used to produce 0 or 1 items.
108 /// **Known problems:** None.
113 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
117 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
121 "used `flat_map` where `filter_map` could be used instead"
124 declare_clippy_lint! {
125 /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
127 /// **Why is this bad?** It is better to handle the `None` or `Err` case,
128 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
129 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
130 /// `Allow` by default.
132 /// `result.unwrap()` will let the thread panic on `Err` values.
133 /// Normally, you want to implement more sophisticated error handling,
134 /// and propagate errors upwards with `?` operator.
136 /// Even if you want to panic on errors, not all `Error`s implement good
137 /// messages on display. Therefore, it may be beneficial to look at the places
138 /// where they may get displayed. Activate this lint to do just that.
140 /// **Known problems:** None.
144 /// # let opt = Some(1);
150 /// opt.expect("more helpful message");
156 /// # let res: Result<usize, ()> = Ok(1);
162 /// res.expect("more helpful message");
166 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
169 declare_clippy_lint! {
170 /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
172 /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
173 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
174 /// this lint is `Allow` by default.
176 /// `result.expect()` will let the thread panic on `Err`
177 /// values. Normally, you want to implement more sophisticated error handling,
178 /// and propagate errors upwards with `?` operator.
180 /// **Known problems:** None.
184 /// # let opt = Some(1);
187 /// opt.expect("one");
190 /// let opt = Some(1);
197 /// # let res: Result<usize, ()> = Ok(1);
200 /// res.expect("one");
204 /// # Ok::<(), ()>(())
208 "using `.expect()` on `Result` or `Option`, which might be better handled"
211 declare_clippy_lint! {
212 /// **What it does:** Checks for methods that should live in a trait
213 /// implementation of a `std` trait (see [llogiq's blog
214 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
215 /// information) instead of an inherent implementation.
217 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
218 /// the code, often with very little cost. Also people seeing a `mul(...)`
220 /// may expect `*` to work equally, so you should have good reason to disappoint
223 /// **Known problems:** None.
229 /// fn add(&self, other: &X) -> X {
235 pub SHOULD_IMPLEMENT_TRAIT,
237 "defining a method that should be implementing a std trait"
240 declare_clippy_lint! {
241 /// **What it does:** Checks for methods with certain name prefixes and which
242 /// doesn't match how self is taken. The actual rules are:
244 /// |Prefix |Postfix |`self` taken | `self` type |
245 /// |-------|------------|-----------------------|--------------|
246 /// |`as_` | none |`&self` or `&mut self` | any |
247 /// |`from_`| none | none | any |
248 /// |`into_`| none |`self` | any |
249 /// |`is_` | none |`&self` or none | any |
250 /// |`to_` | `_mut` |`&mut self` | any |
251 /// |`to_` | not `_mut` |`self` | `Copy` |
252 /// |`to_` | not `_mut` |`&self` | not `Copy` |
254 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
255 /// - Traits definition.
256 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
257 /// - Traits implementation, when `&self` is taken.
258 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
259 /// (see e.g. the `std::string::ToString` trait).
261 /// Please find more info here:
262 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
264 /// **Why is this bad?** Consistency breeds readability. If you follow the
265 /// conventions, your users won't be surprised that they, e.g., need to supply a
266 /// mutable reference to a `as_..` function.
268 /// **Known problems:** None.
274 /// fn as_str(self) -> &'static str {
280 pub WRONG_SELF_CONVENTION,
282 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
285 declare_clippy_lint! {
286 /// **What it does:** This is the same as
287 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
289 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
291 /// **Known problems:** Actually *renaming* the function may break clients if
292 /// the function is part of the public interface. In that case, be mindful of
293 /// the stability guarantees you've given your users.
299 /// pub fn as_str(self) -> &'a str {
304 pub WRONG_PUB_SELF_CONVENTION,
306 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
309 declare_clippy_lint! {
310 /// **What it does:** Checks for usage of `ok().expect(..)`.
312 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
313 /// directly to get a better error message.
315 /// **Known problems:** The error type needs to implement `Debug`
319 /// # let x = Ok::<_, ()>(());
322 /// x.ok().expect("why did I do this again?");
325 /// x.expect("why did I do this again?");
329 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
332 declare_clippy_lint! {
333 /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
334 /// `result.map(_).unwrap_or_else(_)`.
336 /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
337 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
339 /// **Known problems:** The order of the arguments is not in execution order
343 /// # let x = Some(1);
346 /// x.map(|a| a + 1).unwrap_or(0);
349 /// x.map_or(0, |a| a + 1);
355 /// # let x: Result<usize, ()> = Ok(1);
356 /// # fn some_function(foo: ()) -> usize { 1 }
359 /// x.map(|a| a + 1).unwrap_or_else(some_function);
362 /// x.map_or_else(some_function, |a| a + 1);
366 "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)`"
369 declare_clippy_lint! {
370 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
372 /// **Why is this bad?** Readability, this can be written more concisely as
375 /// **Known problems:** The order of the arguments is not in execution order.
379 /// # let opt = Some(1);
382 /// opt.map_or(None, |a| Some(a + 1));
385 /// opt.and_then(|a| Some(a + 1));
387 pub OPTION_MAP_OR_NONE,
389 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
392 declare_clippy_lint! {
393 /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
395 /// **Why is this bad?** Readability, this can be written more concisely as
398 /// **Known problems:** None.
404 /// # let r: Result<u32, &str> = Ok(1);
405 /// assert_eq!(Some(1), r.map_or(None, Some));
410 /// # let r: Result<u32, &str> = Ok(1);
411 /// assert_eq!(Some(1), r.ok());
413 pub RESULT_MAP_OR_INTO_OPTION,
415 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
418 declare_clippy_lint! {
419 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
420 /// `_.or_else(|x| Err(y))`.
422 /// **Why is this bad?** Readability, this can be written more concisely as
423 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
425 /// **Known problems:** None
430 /// # fn opt() -> Option<&'static str> { Some("42") }
431 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
432 /// let _ = opt().and_then(|s| Some(s.len()));
433 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
434 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
437 /// The correct use would be:
440 /// # fn opt() -> Option<&'static str> { Some("42") }
441 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
442 /// let _ = opt().map(|s| s.len());
443 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
444 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
446 pub BIND_INSTEAD_OF_MAP,
448 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
451 declare_clippy_lint! {
452 /// **What it does:** Checks for usage of `_.filter(_).next()`.
454 /// **Why is this bad?** Readability, this can be written more concisely as
457 /// **Known problems:** None.
461 /// # let vec = vec![1];
462 /// vec.iter().filter(|x| **x == 0).next();
464 /// Could be written as
466 /// # let vec = vec![1];
467 /// vec.iter().find(|x| **x == 0);
471 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
474 declare_clippy_lint! {
475 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
477 /// **Why is this bad?** Readability, this can be written more concisely as
478 /// `_.find(!condition)`.
480 /// **Known problems:** None.
484 /// # let vec = vec![1];
485 /// vec.iter().skip_while(|x| **x == 0).next();
487 /// Could be written as
489 /// # let vec = vec![1];
490 /// vec.iter().find(|x| **x != 0);
494 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
497 declare_clippy_lint! {
498 /// **What it does:** Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
500 /// **Why is this bad?** Readability, this can be written more concisely as
503 /// **Known problems:**
507 /// let vec = vec![vec![1]];
510 /// vec.iter().map(|x| x.iter()).flatten();
513 /// vec.iter().flat_map(|x| x.iter());
517 "using combinations of `flatten` and `map` which can usually be written as a single method call"
520 declare_clippy_lint! {
521 /// **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply
522 /// as `filter_map(_)`.
524 /// **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and
527 /// **Known problems:** None.
533 /// .filter(|n| n.checked_add(1).is_some())
534 /// .map(|n| n.checked_add(1).unwrap());
539 /// (0_i32..10).filter_map(|n| n.checked_add(1));
541 pub MANUAL_FILTER_MAP,
543 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
546 declare_clippy_lint! {
547 /// **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply
548 /// as `find_map(_)`.
550 /// **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and
553 /// **Known problems:** None.
559 /// .find(|n| n.checked_add(1).is_some())
560 /// .map(|n| n.checked_add(1).unwrap());
565 /// (0_i32..10).find_map(|n| n.checked_add(1));
569 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
572 declare_clippy_lint! {
573 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
575 /// **Why is this bad?** Readability, this can be written more concisely as
578 /// **Known problems:** None
582 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
584 /// Can be written as
587 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
591 "using combination of `filter_map` and `next` which can usually be written as a single method call"
594 declare_clippy_lint! {
595 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
597 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
599 /// **Known problems:** None
603 /// # let iter = vec![vec![0]].into_iter();
604 /// iter.flat_map(|x| x);
606 /// Can be written as
608 /// # let iter = vec![vec![0]].into_iter();
611 pub FLAT_MAP_IDENTITY,
613 "call to `flat_map` where `flatten` is sufficient"
616 declare_clippy_lint! {
617 /// **What it does:** Checks for an iterator or string search (such as `find()`,
618 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
620 /// **Why is this bad?** Readability, this can be written more concisely as:
621 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
622 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
624 /// **Known problems:** None.
628 /// let vec = vec![1];
629 /// vec.iter().find(|x| **x == 0).is_some();
631 /// let _ = "hello world".find("world").is_none();
633 /// Could be written as
635 /// let vec = vec![1];
636 /// vec.iter().any(|x| *x == 0);
638 /// let _ = !"hello world".contains("world");
642 "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()`)"
645 declare_clippy_lint! {
646 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
647 /// if it starts with a given char.
649 /// **Why is this bad?** Readability, this can be written more concisely as
650 /// `_.starts_with(_)`.
652 /// **Known problems:** None.
656 /// let name = "foo";
657 /// if name.chars().next() == Some('_') {};
659 /// Could be written as
661 /// let name = "foo";
662 /// if name.starts_with('_') {};
666 "using `.chars().next()` to check if a string starts with a char"
669 declare_clippy_lint! {
670 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
671 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
672 /// `unwrap_or_default` instead.
674 /// **Why is this bad?** The function will always be called and potentially
675 /// allocate an object acting as the default.
677 /// **Known problems:** If the function has side-effects, not calling it will
678 /// change the semantic of the program, but you shouldn't rely on that anyway.
682 /// # let foo = Some(String::new());
683 /// foo.unwrap_or(String::new());
685 /// this can instead be written:
687 /// # let foo = Some(String::new());
688 /// foo.unwrap_or_else(String::new);
692 /// # let foo = Some(String::new());
693 /// foo.unwrap_or_default();
697 "using any `*or` method with a function call, which suggests `*or_else`"
700 declare_clippy_lint! {
701 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
702 /// etc., and suggests to use `unwrap_or_else` instead
704 /// **Why is this bad?** The function will always be called.
706 /// **Known problems:** If the function has side-effects, not calling it will
707 /// change the semantics of the program, but you shouldn't rely on that anyway.
711 /// # let foo = Some(String::new());
712 /// # let err_code = "418";
713 /// # let err_msg = "I'm a teapot";
714 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
718 /// # let foo = Some(String::new());
719 /// # let err_code = "418";
720 /// # let err_msg = "I'm a teapot";
721 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
723 /// this can instead be written:
725 /// # let foo = Some(String::new());
726 /// # let err_code = "418";
727 /// # let err_msg = "I'm a teapot";
728 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
732 "using any `expect` method with a function call"
735 declare_clippy_lint! {
736 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
738 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
739 /// generics, not for using the `clone` method on a concrete type.
741 /// **Known problems:** None.
749 "using `clone` on a `Copy` type"
752 declare_clippy_lint! {
753 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
754 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
755 /// function syntax instead (e.g., `Rc::clone(foo)`).
757 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
758 /// can obscure the fact that only the pointer is being cloned, not the underlying
763 /// # use std::rc::Rc;
764 /// let x = Rc::new(1);
772 pub CLONE_ON_REF_PTR,
774 "using 'clone' on a ref-counted pointer"
777 declare_clippy_lint! {
778 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
780 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
781 /// cloning the underlying `T`.
783 /// **Known problems:** None.
790 /// let z = y.clone();
791 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
794 pub CLONE_DOUBLE_REF,
796 "using `clone` on `&&T`"
799 declare_clippy_lint! {
800 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
801 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
803 /// **Why is this bad?** This bypasses the specialized implementation of
804 /// `ToString` and instead goes through the more expensive string formatting
807 /// **Known problems:** None.
811 /// // Generic implementation for `T: Display` is used (slow)
812 /// ["foo", "bar"].iter().map(|s| s.to_string());
814 /// // OK, the specialized impl is used
815 /// ["foo", "bar"].iter().map(|&s| s.to_string());
817 pub INEFFICIENT_TO_STRING,
819 "using `to_string` on `&&T` where `T: ToString`"
822 declare_clippy_lint! {
823 /// **What it does:** Checks for `new` not returning a type that contains `Self`.
825 /// **Why is this bad?** As a convention, `new` methods are used to make a new
826 /// instance of a type.
828 /// **Known problems:** None.
831 /// In an impl block:
834 /// # struct NotAFoo;
836 /// fn new() -> NotAFoo {
846 /// // Bad. The type name must contain `Self`
847 /// fn new() -> Bar {
855 /// # struct FooError;
857 /// // Good. Return type contains `Self`
858 /// fn new() -> Result<Foo, FooError> {
864 /// Or in a trait definition:
866 /// pub trait Trait {
867 /// // Bad. The type name must contain `Self`
873 /// pub trait Trait {
874 /// // Good. Return type contains `Self`
875 /// fn new() -> Self;
880 "not returning type containing `Self` in a `new` method"
883 declare_clippy_lint! {
884 /// **What it does:** Checks for string methods that receive a single-character
885 /// `str` as an argument, e.g., `_.split("x")`.
887 /// **Why is this bad?** Performing these methods using a `char` is faster than
890 /// **Known problems:** Does not catch multi-byte unicode characters.
899 pub SINGLE_CHAR_PATTERN,
901 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
904 declare_clippy_lint! {
905 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
907 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
908 /// actually intend to panic.
910 /// **Known problems:** None.
913 /// ```rust,should_panic
914 /// for x in (0..100).step_by(0) {
918 pub ITERATOR_STEP_BY_ZERO,
920 "using `Iterator::step_by(0)`, which will panic at runtime"
923 declare_clippy_lint! {
924 /// **What it does:** Checks for indirect collection of populated `Option`
926 /// **Why is this bad?** `Option` is like a collection of 0-1 things, so `flatten`
927 /// automatically does this without suspicious-looking `unwrap` calls.
929 /// **Known problems:** None.
934 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
938 /// let _ = std::iter::empty::<Option<i32>>().flatten();
940 pub OPTION_FILTER_MAP,
942 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
945 declare_clippy_lint! {
946 /// **What it does:** Checks for the use of `iter.nth(0)`.
948 /// **Why is this bad?** `iter.next()` is equivalent to
949 /// `iter.nth(0)`, as they both consume the next element,
950 /// but is more readable.
952 /// **Known problems:** None.
957 /// # use std::collections::HashSet;
959 /// # let mut s = HashSet::new();
961 /// let x = s.iter().nth(0);
964 /// # let mut s = HashSet::new();
966 /// let x = s.iter().next();
970 "replace `iter.nth(0)` with `iter.next()`"
973 declare_clippy_lint! {
974 /// **What it does:** Checks for use of `.iter().nth()` (and the related
975 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
977 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
980 /// **Known problems:** None.
984 /// let some_vec = vec![0, 1, 2, 3];
985 /// let bad_vec = some_vec.iter().nth(3);
986 /// let bad_slice = &some_vec[..].iter().nth(3);
988 /// The correct use would be:
990 /// let some_vec = vec![0, 1, 2, 3];
991 /// let bad_vec = some_vec.get(3);
992 /// let bad_slice = &some_vec[..].get(3);
996 "using `.iter().nth()` on a standard library type with O(1) element access"
999 declare_clippy_lint! {
1000 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
1002 /// **Why is this bad?** `.nth(x)` is cleaner
1004 /// **Known problems:** None.
1008 /// let some_vec = vec![0, 1, 2, 3];
1009 /// let bad_vec = some_vec.iter().skip(3).next();
1010 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1012 /// The correct use would be:
1014 /// let some_vec = vec![0, 1, 2, 3];
1015 /// let bad_vec = some_vec.iter().nth(3);
1016 /// let bad_slice = &some_vec[..].iter().nth(3);
1020 "using `.skip(x).next()` on an iterator"
1023 declare_clippy_lint! {
1024 /// **What it does:** Checks for use of `.get().unwrap()` (or
1025 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1027 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
1030 /// **Known problems:** Not a replacement for error handling: Using either
1031 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1032 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1033 /// temporary placeholder for dealing with the `Option` type, then this does
1034 /// not mitigate the need for error handling. If there is a chance that `.get()`
1035 /// will be `None` in your program, then it is advisable that the `None` case
1036 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1041 /// let mut some_vec = vec![0, 1, 2, 3];
1042 /// let last = some_vec.get(3).unwrap();
1043 /// *some_vec.get_mut(0).unwrap() = 1;
1045 /// The correct use would be:
1047 /// let mut some_vec = vec![0, 1, 2, 3];
1048 /// let last = some_vec[3];
1049 /// some_vec[0] = 1;
1053 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1056 declare_clippy_lint! {
1057 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
1058 /// `&str` or `String`.
1060 /// **Why is this bad?** `.push_str(s)` is clearer
1062 /// **Known problems:** None.
1066 /// let abc = "abc";
1067 /// let def = String::from("def");
1068 /// let mut s = String::new();
1069 /// s.extend(abc.chars());
1070 /// s.extend(def.chars());
1072 /// The correct use would be:
1074 /// let abc = "abc";
1075 /// let def = String::from("def");
1076 /// let mut s = String::new();
1077 /// s.push_str(abc);
1078 /// s.push_str(&def);
1080 pub STRING_EXTEND_CHARS,
1082 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1085 declare_clippy_lint! {
1086 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
1089 /// **Why is this bad?** `.to_vec()` is clearer
1091 /// **Known problems:** None.
1095 /// let s = [1, 2, 3, 4, 5];
1096 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1098 /// The better use would be:
1100 /// let s = [1, 2, 3, 4, 5];
1101 /// let s2: Vec<isize> = s.to_vec();
1103 pub ITER_CLONED_COLLECT,
1105 "using `.cloned().collect()` on slice to create a `Vec`"
1108 declare_clippy_lint! {
1109 /// **What it does:** Checks for usage of `_.chars().last()` or
1110 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1112 /// **Why is this bad?** Readability, this can be written more concisely as
1113 /// `_.ends_with(_)`.
1115 /// **Known problems:** None.
1119 /// # let name = "_";
1122 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1125 /// name.ends_with('_') || name.ends_with('-');
1129 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1132 declare_clippy_lint! {
1133 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
1134 /// types before and after the call are the same.
1136 /// **Why is this bad?** The call is unnecessary.
1138 /// **Known problems:** None.
1142 /// # fn do_stuff(x: &[i32]) {}
1143 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1144 /// do_stuff(x.as_ref());
1146 /// The correct use would be:
1148 /// # fn do_stuff(x: &[i32]) {}
1149 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1154 "using `as_ref` where the types before and after the call are the same"
1157 declare_clippy_lint! {
1158 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1159 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1160 /// `sum` or `product`.
1162 /// **Why is this bad?** Readability.
1164 /// **Known problems:** None.
1168 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1170 /// This could be written as:
1172 /// let _ = (0..3).any(|x| x > 2);
1174 pub UNNECESSARY_FOLD,
1176 "using `fold` when a more succinct alternative exists"
1179 declare_clippy_lint! {
1180 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1181 /// More specifically it checks if the closure provided is only performing one of the
1182 /// filter or map operations and suggests the appropriate option.
1184 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1185 /// operation is being performed.
1187 /// **Known problems:** None
1191 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1193 /// // As there is no transformation of the argument this could be written as:
1194 /// let _ = (0..3).filter(|&x| x > 2);
1198 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1200 /// // As there is no conditional check on the argument this could be written as:
1201 /// let _ = (0..4).map(|x| x + 1);
1203 pub UNNECESSARY_FILTER_MAP,
1205 "using `filter_map` when a more succinct alternative exists"
1208 declare_clippy_lint! {
1209 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1212 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1213 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1214 /// `iter_mut` directly.
1216 /// **Known problems:** None
1222 /// let _ = (&vec![3, 4, 5]).into_iter();
1225 /// let _ = (&vec![3, 4, 5]).iter();
1227 pub INTO_ITER_ON_REF,
1229 "using `.into_iter()` on a reference"
1232 declare_clippy_lint! {
1233 /// **What it does:** Checks for calls to `map` followed by a `count`.
1235 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1236 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1237 /// drive the iterator to completion, you can just use `for_each` instead.
1239 /// **Known problems:** None
1244 /// let _ = (0..3).map(|x| x + 2).count();
1248 "suspicious usage of map"
1251 declare_clippy_lint! {
1252 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1254 /// **Why is this bad?** For most types, this is undefined behavior.
1256 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1257 /// of `MaybeUninit`. There may be other types that allow uninitialized
1258 /// data, but those are not yet rigorously defined.
1263 /// // Beware the UB
1264 /// use std::mem::MaybeUninit;
1266 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1269 /// Note that the following is OK:
1272 /// use std::mem::MaybeUninit;
1274 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1275 /// MaybeUninit::uninit().assume_init()
1278 pub UNINIT_ASSUMED_INIT,
1280 "`MaybeUninit::uninit().assume_init()`"
1283 declare_clippy_lint! {
1284 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1286 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1291 /// # let y: u32 = 0;
1292 /// # let x: u32 = 100;
1293 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1294 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1297 /// can be written using dedicated methods for saturating addition/subtraction as:
1300 /// # let y: u32 = 0;
1301 /// # let x: u32 = 100;
1302 /// let add = x.saturating_add(y);
1303 /// let sub = x.saturating_sub(y);
1305 pub MANUAL_SATURATING_ARITHMETIC,
1307 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1310 declare_clippy_lint! {
1311 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1312 /// zero-sized types
1314 /// **Why is this bad?** This is a no-op, and likely unintended
1316 /// **Known problems:** None
1320 /// unsafe { (&() as *const ()).offset(1) };
1324 "Check for offset calculations on raw pointers to zero-sized types"
1327 declare_clippy_lint! {
1328 /// **What it does:** Checks for `FileType::is_file()`.
1330 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1331 /// they are testing whether a path is something they can get bytes from. But
1332 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1333 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1339 /// let metadata = std::fs::metadata("foo.txt")?;
1340 /// let filetype = metadata.file_type();
1342 /// if filetype.is_file() {
1345 /// # Ok::<_, std::io::Error>(())
1349 /// should be written as:
1353 /// let metadata = std::fs::metadata("foo.txt")?;
1354 /// let filetype = metadata.file_type();
1356 /// if !filetype.is_dir() {
1359 /// # Ok::<_, std::io::Error>(())
1362 pub FILETYPE_IS_FILE,
1364 "`FileType::is_file` is not recommended to test for readable file type"
1367 declare_clippy_lint! {
1368 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1370 /// **Why is this bad?** Readability, this can be written more concisely as
1373 /// **Known problems:** None.
1377 /// # let opt = Some("".to_string());
1378 /// opt.as_ref().map(String::as_str)
1381 /// Can be written as
1383 /// # let opt = Some("".to_string());
1387 pub OPTION_AS_REF_DEREF,
1389 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1392 declare_clippy_lint! {
1393 /// **What it does:** Checks for usage of `iter().next()` on a Slice or an Array
1395 /// **Why is this bad?** These can be shortened into `.get()`
1397 /// **Known problems:** None.
1401 /// # let a = [1, 2, 3];
1402 /// # let b = vec![1, 2, 3];
1403 /// a[2..].iter().next();
1404 /// b.iter().next();
1406 /// should be written as:
1408 /// # let a = [1, 2, 3];
1409 /// # let b = vec![1, 2, 3];
1413 pub ITER_NEXT_SLICE,
1415 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1418 declare_clippy_lint! {
1419 /// **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal
1420 /// where `push`/`insert` with a `char` would work fine.
1422 /// **Why is this bad?** It's less clear that we are pushing a single character.
1424 /// **Known problems:** None
1428 /// let mut string = String::new();
1429 /// string.insert_str(0, "R");
1430 /// string.push_str("R");
1432 /// Could be written as
1434 /// let mut string = String::new();
1435 /// string.insert(0, 'R');
1436 /// string.push('R');
1438 pub SINGLE_CHAR_ADD_STR,
1440 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1443 declare_clippy_lint! {
1444 /// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1445 /// lazily evaluated closures on `Option` and `Result`.
1447 /// This lint suggests changing the following functions, when eager evaluation results in
1449 /// - `unwrap_or_else` to `unwrap_or`
1450 /// - `and_then` to `and`
1451 /// - `or_else` to `or`
1452 /// - `get_or_insert_with` to `get_or_insert`
1453 /// - `ok_or_else` to `ok_or`
1455 /// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1457 /// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1458 /// side effects. Eagerly evaluating them can change the semantics of the program.
1463 /// // example code where clippy issues a warning
1464 /// let opt: Option<u32> = None;
1466 /// opt.unwrap_or_else(|| 42);
1470 /// let opt: Option<u32> = None;
1472 /// opt.unwrap_or(42);
1474 pub UNNECESSARY_LAZY_EVALUATIONS,
1476 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1479 declare_clippy_lint! {
1480 /// **What it does:** Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1482 /// **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.
1484 /// **Known problems:** None
1489 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1493 /// (0..3).try_for_each(|t| Err(t));
1495 pub MAP_COLLECT_RESULT_UNIT,
1497 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1500 declare_clippy_lint! {
1501 /// **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator`
1504 /// **Why is this bad?** It is recommended style to use collect. See
1505 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1507 /// **Known problems:** None.
1512 /// use std::iter::FromIterator;
1514 /// let five_fives = std::iter::repeat(5).take(5);
1516 /// let v = Vec::from_iter(five_fives);
1518 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1522 /// let five_fives = std::iter::repeat(5).take(5);
1524 /// let v: Vec<i32> = five_fives.collect();
1526 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1528 pub FROM_ITER_INSTEAD_OF_COLLECT,
1530 "use `.collect()` instead of `::from_iter()`"
1533 declare_clippy_lint! {
1534 /// **What it does:** Checks for usage of `inspect().for_each()`.
1536 /// **Why is this bad?** It is the same as performing the computation
1537 /// inside `inspect` at the beginning of the closure in `for_each`.
1539 /// **Known problems:** None.
1544 /// [1,2,3,4,5].iter()
1545 /// .inspect(|&x| println!("inspect the number: {}", x))
1546 /// .for_each(|&x| {
1547 /// assert!(x >= 0);
1550 /// Can be written as
1552 /// [1,2,3,4,5].iter()
1553 /// .for_each(|&x| {
1554 /// println!("inspect the number: {}", x);
1555 /// assert!(x >= 0);
1558 pub INSPECT_FOR_EACH,
1560 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1563 declare_clippy_lint! {
1564 /// **What it does:** Checks for usage of `filter_map(|x| x)`.
1566 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
1568 /// **Known problems:** None.
1573 /// # let iter = vec![Some(1)].into_iter();
1574 /// iter.filter_map(|x| x);
1578 /// # let iter = vec![Some(1)].into_iter();
1581 pub FILTER_MAP_IDENTITY,
1583 "call to `filter_map` where `flatten` is sufficient"
1586 declare_clippy_lint! {
1587 /// **What it does:** Checks for the use of `.bytes().nth()`.
1589 /// **Why is this bad?** `.as_bytes().get()` is more efficient and more
1592 /// **Known problems:** None.
1598 /// let _ = "Hello".bytes().nth(3);
1601 /// let _ = "Hello".as_bytes().get(3);
1605 "replace `.bytes().nth()` with `.as_bytes().get()`"
1608 declare_clippy_lint! {
1609 /// **What it does:** Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1611 /// **Why is this bad?** These methods do the same thing as `_.clone()` but may be confusing as
1612 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1614 /// **Known problems:** None.
1619 /// let a = vec![1, 2, 3];
1620 /// let b = a.to_vec();
1621 /// let c = a.to_owned();
1625 /// let a = vec![1, 2, 3];
1626 /// let b = a.clone();
1627 /// let c = a.clone();
1631 "implicitly cloning a value by invoking a function on its dereferenced type"
1634 declare_clippy_lint! {
1635 /// **What it does:** Checks for the use of `.iter().count()`.
1637 /// **Why is this bad?** `.len()` is more efficient and more
1640 /// **Known problems:** None.
1646 /// let some_vec = vec![0, 1, 2, 3];
1647 /// let _ = some_vec.iter().count();
1648 /// let _ = &some_vec[..].iter().count();
1651 /// let some_vec = vec![0, 1, 2, 3];
1652 /// let _ = some_vec.len();
1653 /// let _ = &some_vec[..].len();
1657 "replace `.iter().count()` with `.len()`"
1660 pub struct Methods {
1661 msrv: Option<RustcVersion>,
1666 pub fn new(msrv: Option<RustcVersion>) -> Self {
1671 impl_lint_pass!(Methods => [
1674 SHOULD_IMPLEMENT_TRAIT,
1675 WRONG_SELF_CONVENTION,
1676 WRONG_PUB_SELF_CONVENTION,
1679 RESULT_MAP_OR_INTO_OPTION,
1681 BIND_INSTEAD_OF_MAP,
1689 CLONED_INSTEAD_OF_COPIED,
1691 INEFFICIENT_TO_STRING,
1693 SINGLE_CHAR_PATTERN,
1694 SINGLE_CHAR_ADD_STR,
1698 FILTER_MAP_IDENTITY,
1705 ITERATOR_STEP_BY_ZERO,
1713 STRING_EXTEND_CHARS,
1714 ITER_CLONED_COLLECT,
1717 UNNECESSARY_FILTER_MAP,
1720 UNINIT_ASSUMED_INIT,
1721 MANUAL_SATURATING_ARITHMETIC,
1724 OPTION_AS_REF_DEREF,
1725 UNNECESSARY_LAZY_EVALUATIONS,
1726 MAP_COLLECT_RESULT_UNIT,
1727 FROM_ITER_INSTEAD_OF_COLLECT,
1732 /// Extracts a method call name, args, and `Span` of the method name.
1733 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(SymbolStr, &'tcx [hir::Expr<'tcx>], Span)> {
1734 if let ExprKind::MethodCall(path, span, args, _) = recv.kind {
1735 if !args.iter().any(|e| e.span.from_expansion()) {
1736 return Some((path.ident.name.as_str(), args, span));
1742 /// Same as `method_call` but the `SymbolStr` is dereferenced into a temporary `&str`
1743 macro_rules! method_call {
1747 .map(|&(ref name, args, span)| (&**name, args, span))
1751 impl<'tcx> LateLintPass<'tcx> for Methods {
1752 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1753 if in_macro(expr.span) {
1757 check_methods(cx, expr, self.msrv.as_ref());
1760 hir::ExprKind::Call(func, args) => {
1761 from_iter_instead_of_collect::check(cx, expr, args, func);
1763 hir::ExprKind::MethodCall(method_call, ref method_span, args, _) => {
1764 or_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1765 expect_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1766 clone_on_copy::check(cx, expr, method_call.ident.name, args);
1767 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
1768 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
1769 single_char_add_str::check(cx, expr, args);
1770 into_iter_on_ref::check(cx, expr, *method_span, method_call.ident.name, args);
1771 single_char_pattern::check(cx, expr, method_call.ident.name, args);
1773 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
1774 let mut info = BinaryExprInfo {
1778 eq: op.node == hir::BinOpKind::Eq,
1780 lint_binary_expr_with_method_call(cx, &mut info);
1786 #[allow(clippy::too_many_lines)]
1787 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1788 if in_external_macro(cx.sess(), impl_item.span) {
1791 let name = impl_item.ident.name.as_str();
1792 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
1793 let item = cx.tcx.hir().expect_item(parent);
1794 let self_ty = cx.tcx.type_of(item.def_id);
1796 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
1798 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1799 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
1801 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
1802 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1804 let first_arg_ty = &method_sig.inputs().iter().next();
1806 // check conventions w.r.t. conversion method names and predicates
1807 if let Some(first_arg_ty) = first_arg_ty;
1810 // if this impl block implements a trait, lint in trait definition instead
1811 if !implements_trait && cx.access_levels.is_exported(impl_item.hir_id()) {
1812 // check missing trait implementations
1813 for method_config in &TRAIT_METHODS {
1814 if name == method_config.method_name &&
1815 sig.decl.inputs.len() == method_config.param_count &&
1816 method_config.output_type.matches(&sig.decl.output) &&
1817 method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1818 fn_header_equals(method_config.fn_header, sig.header) &&
1819 method_config.lifetime_param_cond(impl_item)
1823 SHOULD_IMPLEMENT_TRAIT,
1826 "method `{}` can be confused for the standard trait method `{}::{}`",
1827 method_config.method_name,
1828 method_config.trait_name,
1829 method_config.method_name
1833 "consider implementing the trait `{}` or choosing a less ambiguous method name",
1834 method_config.trait_name
1841 if sig.decl.implicit_self.has_implicit_self() {
1842 wrong_self_convention::check(
1845 item.vis.node.is_pub(),
1856 // if this impl block implements a trait, lint in trait definition instead
1857 if implements_trait {
1861 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1862 let ret_ty = return_ty(cx, impl_item.hir_id());
1864 // walk the return type and check for Self (this does not check associated types)
1865 if let Some(self_adt) = self_ty.ty_adt_def() {
1866 if contains_adt_constructor(ret_ty, self_adt) {
1869 } else if contains_ty(ret_ty, self_ty) {
1873 // if return type is impl trait, check the associated types
1874 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
1875 // one of the associated types must be Self
1876 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
1877 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1878 // walk the associated type and check for Self
1879 if let Some(self_adt) = self_ty.ty_adt_def() {
1880 if contains_adt_constructor(projection_predicate.ty, self_adt) {
1883 } else if contains_ty(projection_predicate.ty, self_ty) {
1890 if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1895 "methods called `new` usually return `Self`",
1901 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1902 if in_external_macro(cx.tcx.sess, item.span) {
1907 if let TraitItemKind::Fn(ref sig, _) = item.kind;
1908 if sig.decl.implicit_self.has_implicit_self();
1909 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
1912 let first_arg_span = first_arg_ty.span;
1913 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
1914 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1915 wrong_self_convention::check(
1917 &item.ident.name.as_str(),
1929 if item.ident.name == sym::new;
1930 if let TraitItemKind::Fn(_, _) = item.kind;
1931 let ret_ty = return_ty(cx, item.hir_id());
1932 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1933 if !contains_ty(ret_ty, self_ty);
1940 "methods called `new` usually return `Self`",
1946 extract_msrv_attr!(LateContext);
1949 #[allow(clippy::too_many_lines)]
1950 fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Option<&RustcVersion>) {
1951 if let Some((name, [recv, args @ ..], span)) = method_call!(expr) {
1952 match (name, args) {
1953 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [recv, _]) => {
1954 zst_offset::check(cx, expr, recv)
1956 ("and_then", [arg]) => {
1957 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
1958 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
1959 if !biom_option_linted && !biom_result_linted {
1960 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
1963 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
1964 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
1965 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
1966 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, msrv),
1967 ("collect", []) => match method_call!(recv) {
1968 Some(("cloned", [recv2], _)) => iter_cloned_collect::check(cx, expr, recv2),
1969 Some(("map", [m_recv, m_arg], _)) => {
1970 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
1974 ("count", []) => match method_call!(recv) {
1975 Some((name @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
1976 iter_count::check(cx, expr, recv2, name);
1978 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
1981 ("expect", [_]) => match method_call!(recv) {
1982 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
1983 _ => expect_used::check(cx, expr, recv),
1985 ("extend", [arg]) => string_extend_chars::check(cx, expr, recv, arg),
1986 ("filter_map", [arg]) => {
1987 unnecessary_filter_map::check(cx, expr, arg);
1988 filter_map_identity::check(cx, expr, arg, span);
1990 ("flat_map", [arg]) => {
1991 flat_map_identity::check(cx, expr, arg, span);
1992 flat_map_option::check(cx, expr, arg, span);
1994 ("flatten", []) => {
1995 if let Some(("map", [recv, map_arg], _)) = method_call!(recv) {
1996 map_flatten::check(cx, expr, recv, map_arg);
1999 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2000 ("for_each", [_]) => {
2001 if let Some(("inspect", [_, _], span2)) = method_call!(recv) {
2002 inspect_for_each::check(cx, expr, span2);
2005 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2006 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2007 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2008 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2009 ("map", [m_arg]) => {
2010 if let Some((name, [recv2, args @ ..], span2)) = method_call!(recv) {
2011 match (name, args) {
2012 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, msrv),
2013 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, msrv),
2014 ("filter", [f_arg]) => {
2015 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false)
2017 ("find", [f_arg]) => filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true),
2022 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2024 if let Some((name, [recv, args @ ..], _)) = method_call!(recv) {
2025 match (name, args) {
2026 ("filter", [arg]) => filter_next::check(cx, expr, recv, arg),
2027 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv, arg, msrv),
2028 ("iter", []) => iter_next_slice::check(cx, expr, recv),
2029 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv, arg),
2030 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2035 ("nth", [n_arg]) => match method_call!(recv) {
2036 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2037 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2038 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2039 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2041 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2042 ("or_else", [arg]) => {
2043 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2044 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2047 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2048 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2049 implicit_clone::check(cx, name, expr, recv, span);
2051 ("unwrap", []) => match method_call!(recv) {
2052 Some(("get", [recv, get_arg], _)) => get_unwrap::check(cx, expr, recv, get_arg, false),
2053 Some(("get_mut", [recv, get_arg], _)) => get_unwrap::check(cx, expr, recv, get_arg, true),
2054 _ => unwrap_used::check(cx, expr, recv),
2056 ("unwrap_or", [u_arg]) => match method_call!(recv) {
2057 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2058 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2060 Some(("map", [m_recv, m_arg], span)) => {
2061 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span)
2065 ("unwrap_or_else", [u_arg]) => match method_call!(recv) {
2066 Some(("map", [recv, map_arg], _)) if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, msrv) => {},
2067 _ => unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or"),
2074 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2075 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call!(recv) {
2076 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span)
2080 /// Used for `lint_binary_expr_with_method_call`.
2081 #[derive(Copy, Clone)]
2082 struct BinaryExprInfo<'a> {
2083 expr: &'a hir::Expr<'a>,
2084 chain: &'a hir::Expr<'a>,
2085 other: &'a hir::Expr<'a>,
2089 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2090 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2091 macro_rules! lint_with_both_lhs_and_rhs {
2092 ($func:expr, $cx:expr, $info:ident) => {
2093 if !$func($cx, $info) {
2094 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2095 if $func($cx, $info) {
2102 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2103 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2104 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2105 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2108 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2109 unsafety: hir::Unsafety::Normal,
2110 constness: hir::Constness::NotConst,
2111 asyncness: hir::IsAsync::NotAsync,
2112 abi: rustc_target::spec::abi::Abi::Rust,
2115 struct ShouldImplTraitCase {
2116 trait_name: &'static str,
2117 method_name: &'static str,
2119 fn_header: hir::FnHeader,
2120 // implicit self kind expected (none, self, &self, ...)
2121 self_kind: SelfKind,
2122 // checks against the output type
2123 output_type: OutType,
2124 // certain methods with explicit lifetimes can't implement the equivalent trait method
2125 lint_explicit_lifetime: bool,
2127 impl ShouldImplTraitCase {
2129 trait_name: &'static str,
2130 method_name: &'static str,
2132 fn_header: hir::FnHeader,
2133 self_kind: SelfKind,
2134 output_type: OutType,
2135 lint_explicit_lifetime: bool,
2136 ) -> ShouldImplTraitCase {
2137 ShouldImplTraitCase {
2144 lint_explicit_lifetime,
2148 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2149 self.lint_explicit_lifetime
2150 || !impl_item.generics.params.iter().any(|p| {
2153 hir::GenericParamKind::Lifetime {
2154 kind: hir::LifetimeParamKind::Explicit
2162 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2163 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2164 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2165 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2166 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2167 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2168 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2169 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2170 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2171 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2172 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2173 // FIXME: default doesn't work
2174 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2175 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2176 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2177 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2178 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2179 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2180 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2181 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2182 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2183 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2184 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2185 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2186 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2187 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2188 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2189 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2190 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2191 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2192 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2193 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2196 #[derive(Clone, Copy, PartialEq, Debug)]
2205 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2206 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2207 if ty == parent_ty {
2209 } else if ty.is_box() {
2210 ty.boxed_ty() == parent_ty
2211 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2212 if let ty::Adt(_, substs) = ty.kind() {
2213 substs.types().next().map_or(false, |t| t == parent_ty)
2222 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2223 if let ty::Ref(_, t, m) = *ty.kind() {
2224 return m == mutability && t == parent_ty;
2227 let trait_path = match mutability {
2228 hir::Mutability::Not => &paths::ASREF_TRAIT,
2229 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2232 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2234 None => return false,
2236 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2240 Self::Value => matches_value(cx, parent_ty, ty),
2241 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2242 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2243 Self::No => ty != parent_ty,
2248 fn description(self) -> &'static str {
2250 Self::Value => "`self` by value",
2251 Self::Ref => "`self` by reference",
2252 Self::RefMut => "`self` by mutable reference",
2253 Self::No => "no `self`",
2258 #[derive(Clone, Copy)]
2267 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2268 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2270 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2271 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2272 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2273 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2274 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2280 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2281 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2282 matches!(path.res, Res::PrimTy(PrimTy::Bool))
2288 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2289 expected.constness == actual.constness
2290 && expected.unsafety == actual.unsafety
2291 && expected.asyncness == actual.asyncness