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;
14 mod extend_with_drain;
17 mod filter_map_identity;
20 mod flat_map_identity;
22 mod from_iter_instead_of_collect;
25 mod inefficient_to_string;
28 mod iter_cloned_collect;
34 mod iterator_step_by_zero;
35 mod manual_saturating_arithmetic;
36 mod manual_split_once;
37 mod manual_str_repeat;
38 mod map_collect_result_unit;
43 mod option_as_ref_deref;
44 mod option_map_or_none;
45 mod option_map_unwrap_or;
48 mod single_char_add_str;
49 mod single_char_insert_string;
50 mod single_char_pattern;
51 mod single_char_push_string;
53 mod string_extend_chars;
55 mod suspicious_splitn;
56 mod uninit_assumed_init;
57 mod unnecessary_filter_map;
59 mod unnecessary_lazy_eval;
60 mod unwrap_or_else_default;
64 mod wrong_self_convention;
67 use bind_instead_of_map::BindInsteadOfMap;
68 use clippy_utils::consts::{constant, Constant};
69 use clippy_utils::diagnostics::{span_lint, span_lint_and_help};
70 use clippy_utils::ty::{contains_adt_constructor, contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
71 use clippy_utils::{contains_return, get_trait_def_id, in_macro, iter_input_pats, meets_msrv, msrvs, paths, return_ty};
72 use if_chain::if_chain;
74 use rustc_hir::def::Res;
75 use rustc_hir::{Expr, ExprKind, PrimTy, QPath, TraitItem, TraitItemKind};
76 use rustc_lint::{LateContext, LateLintPass, LintContext};
77 use rustc_middle::lint::in_external_macro;
78 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
79 use rustc_semver::RustcVersion;
80 use rustc_session::{declare_tool_lint, impl_lint_pass};
81 use rustc_span::symbol::SymbolStr;
82 use rustc_span::{sym, Span};
83 use rustc_typeck::hir_ty_to_ty;
85 declare_clippy_lint! {
87 /// Checks for usages of `cloned()` on an `Iterator` or `Option` where
88 /// `copied()` could be used instead.
90 /// ### Why is this bad?
91 /// `copied()` is better because it guarantees that the type being cloned
92 /// implements `Copy`.
96 /// [1, 2, 3].iter().cloned();
100 /// [1, 2, 3].iter().copied();
102 pub CLONED_INSTEAD_OF_COPIED,
104 "used `cloned` where `copied` could be used instead"
107 declare_clippy_lint! {
109 /// Checks for usages of `Iterator::flat_map()` where `filter_map()` could be
112 /// ### Why is this bad?
113 /// When applicable, `filter_map()` is more clear since it shows that
114 /// `Option` is used to produce 0 or 1 items.
118 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().flat_map(|x| x.parse().ok()).collect();
122 /// let nums: Vec<i32> = ["1", "2", "whee!"].iter().filter_map(|x| x.parse().ok()).collect();
126 "used `flat_map` where `filter_map` could be used instead"
129 declare_clippy_lint! {
131 /// Checks for `.unwrap()` calls on `Option`s and on `Result`s.
133 /// ### Why is this bad?
134 /// It is better to handle the `None` or `Err` case,
135 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
136 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
137 /// `Allow` by default.
139 /// `result.unwrap()` will let the thread panic on `Err` values.
140 /// Normally, you want to implement more sophisticated error handling,
141 /// and propagate errors upwards with `?` operator.
143 /// Even if you want to panic on errors, not all `Error`s implement good
144 /// messages on display. Therefore, it may be beneficial to look at the places
145 /// where they may get displayed. Activate this lint to do just that.
149 /// # let opt = Some(1);
155 /// opt.expect("more helpful message");
161 /// # let res: Result<usize, ()> = Ok(1);
167 /// res.expect("more helpful message");
171 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
174 declare_clippy_lint! {
176 /// Checks for `.expect()` calls on `Option`s and `Result`s.
178 /// ### Why is this bad?
179 /// Usually it is better to handle the `None` or `Err` case.
180 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
181 /// this lint is `Allow` by default.
183 /// `result.expect()` will let the thread panic on `Err`
184 /// values. Normally, you want to implement more sophisticated error handling,
185 /// and propagate errors upwards with `?` operator.
189 /// # let opt = Some(1);
192 /// opt.expect("one");
195 /// let opt = Some(1);
202 /// # let res: Result<usize, ()> = Ok(1);
205 /// res.expect("one");
209 /// # Ok::<(), ()>(())
213 "using `.expect()` on `Result` or `Option`, which might be better handled"
216 declare_clippy_lint! {
218 /// Checks for methods that should live in a trait
219 /// implementation of a `std` trait (see [llogiq's blog
220 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
221 /// information) instead of an inherent implementation.
223 /// ### Why is this bad?
224 /// Implementing the traits improve ergonomics for users of
225 /// the code, often with very little cost. Also people seeing a `mul(...)`
227 /// may expect `*` to work equally, so you should have good reason to disappoint
234 /// fn add(&self, other: &X) -> X {
240 pub SHOULD_IMPLEMENT_TRAIT,
242 "defining a method that should be implementing a std trait"
245 declare_clippy_lint! {
247 /// Checks for methods with certain name prefixes and which
248 /// doesn't match how self is taken. The actual rules are:
250 /// |Prefix |Postfix |`self` taken | `self` type |
251 /// |-------|------------|-----------------------|--------------|
252 /// |`as_` | none |`&self` or `&mut self` | any |
253 /// |`from_`| none | none | any |
254 /// |`into_`| none |`self` | any |
255 /// |`is_` | none |`&self` or none | any |
256 /// |`to_` | `_mut` |`&mut self` | any |
257 /// |`to_` | not `_mut` |`self` | `Copy` |
258 /// |`to_` | not `_mut` |`&self` | not `Copy` |
260 /// Note: Clippy doesn't trigger methods with `to_` prefix in:
261 /// - Traits definition.
262 /// Clippy can not tell if a type that implements a trait is `Copy` or not.
263 /// - Traits implementation, when `&self` is taken.
264 /// The method signature is controlled by the trait and often `&self` is required for all types that implement the trait
265 /// (see e.g. the `std::string::ToString` trait).
267 /// Clippy allows `Pin<&Self>` and `Pin<&mut Self>` if `&self` and `&mut self` is required.
269 /// Please find more info here:
270 /// https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
272 /// ### Why is this bad?
273 /// Consistency breeds readability. If you follow the
274 /// conventions, your users won't be surprised that they, e.g., need to supply a
275 /// mutable reference to a `as_..` function.
281 /// fn as_str(self) -> &'static str {
287 pub WRONG_SELF_CONVENTION,
289 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
292 declare_clippy_lint! {
294 /// Checks for usage of `ok().expect(..)`.
296 /// ### Why is this bad?
297 /// Because you usually call `expect()` on the `Result`
298 /// directly to get a better error message.
300 /// ### Known problems
301 /// The error type needs to implement `Debug`
305 /// # let x = Ok::<_, ()>(());
308 /// x.ok().expect("why did I do this again?");
311 /// x.expect("why did I do this again?");
315 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
318 declare_clippy_lint! {
320 /// Checks for usages of `_.unwrap_or_else(Default::default)` on `Option` and
323 /// ### Why is this bad?
324 /// Readability, these can be written as `_.unwrap_or_default`, which is
325 /// simpler and more concise.
329 /// # let x = Some(1);
332 /// x.unwrap_or_else(Default::default);
333 /// x.unwrap_or_else(u32::default);
336 /// x.unwrap_or_default();
338 pub UNWRAP_OR_ELSE_DEFAULT,
340 "using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
343 declare_clippy_lint! {
345 /// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
346 /// `result.map(_).unwrap_or_else(_)`.
348 /// ### Why is this bad?
349 /// Readability, these can be written more concisely (resp.) as
350 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
352 /// ### Known problems
353 /// The order of the arguments is not in execution order
357 /// # let x = Some(1);
360 /// x.map(|a| a + 1).unwrap_or(0);
363 /// x.map_or(0, |a| a + 1);
369 /// # let x: Result<usize, ()> = Ok(1);
370 /// # fn some_function(foo: ()) -> usize { 1 }
373 /// x.map(|a| a + 1).unwrap_or_else(some_function);
376 /// x.map_or_else(some_function, |a| a + 1);
380 "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)`"
383 declare_clippy_lint! {
385 /// Checks for usage of `_.map_or(None, _)`.
387 /// ### Why is this bad?
388 /// Readability, this can be written more concisely as
391 /// ### Known problems
392 /// The order of the arguments is not in execution order.
396 /// # let opt = Some(1);
399 /// opt.map_or(None, |a| Some(a + 1));
402 /// opt.and_then(|a| Some(a + 1));
404 pub OPTION_MAP_OR_NONE,
406 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
409 declare_clippy_lint! {
411 /// Checks for usage of `_.map_or(None, Some)`.
413 /// ### Why is this bad?
414 /// Readability, this can be written more concisely as
420 /// # let r: Result<u32, &str> = Ok(1);
421 /// assert_eq!(Some(1), r.map_or(None, Some));
426 /// # let r: Result<u32, &str> = Ok(1);
427 /// assert_eq!(Some(1), r.ok());
429 pub RESULT_MAP_OR_INTO_OPTION,
431 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
434 declare_clippy_lint! {
436 /// Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
437 /// `_.or_else(|x| Err(y))`.
439 /// ### Why is this bad?
440 /// Readability, this can be written more concisely as
441 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
445 /// # fn opt() -> Option<&'static str> { Some("42") }
446 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
447 /// let _ = opt().and_then(|s| Some(s.len()));
448 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
449 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
452 /// The correct use would be:
455 /// # fn opt() -> Option<&'static str> { Some("42") }
456 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
457 /// let _ = opt().map(|s| s.len());
458 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
459 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
461 pub BIND_INSTEAD_OF_MAP,
463 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
466 declare_clippy_lint! {
468 /// Checks for usage of `_.filter(_).next()`.
470 /// ### Why is this bad?
471 /// Readability, this can be written more concisely as
476 /// # let vec = vec![1];
477 /// vec.iter().filter(|x| **x == 0).next();
479 /// Could be written as
481 /// # let vec = vec![1];
482 /// vec.iter().find(|x| **x == 0);
486 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
489 declare_clippy_lint! {
491 /// Checks for usage of `_.skip_while(condition).next()`.
493 /// ### Why is this bad?
494 /// Readability, this can be written more concisely as
495 /// `_.find(!condition)`.
499 /// # let vec = vec![1];
500 /// vec.iter().skip_while(|x| **x == 0).next();
502 /// Could be written as
504 /// # let vec = vec![1];
505 /// vec.iter().find(|x| **x != 0);
509 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
512 declare_clippy_lint! {
514 /// Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
516 /// ### Why is this bad?
517 /// Readability, this can be written more concisely as
522 /// let vec = vec![vec![1]];
525 /// vec.iter().map(|x| x.iter()).flatten();
528 /// vec.iter().flat_map(|x| x.iter());
532 "using combinations of `flatten` and `map` which can usually be written as a single method call"
535 declare_clippy_lint! {
537 /// Checks for usage of `_.filter(_).map(_)` that can be written more simply
538 /// as `filter_map(_)`.
540 /// ### Why is this bad?
541 /// Redundant code in the `filter` and `map` operations is poor style and
548 /// .filter(|n| n.checked_add(1).is_some())
549 /// .map(|n| n.checked_add(1).unwrap());
554 /// (0_i32..10).filter_map(|n| n.checked_add(1));
556 pub MANUAL_FILTER_MAP,
558 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
561 declare_clippy_lint! {
563 /// Checks for usage of `_.find(_).map(_)` that can be written more simply
564 /// as `find_map(_)`.
566 /// ### Why is this bad?
567 /// Redundant code in the `find` and `map` operations is poor style and
574 /// .find(|n| n.checked_add(1).is_some())
575 /// .map(|n| n.checked_add(1).unwrap());
580 /// (0_i32..10).find_map(|n| n.checked_add(1));
584 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
587 declare_clippy_lint! {
589 /// Checks for usage of `_.filter_map(_).next()`.
591 /// ### Why is this bad?
592 /// Readability, this can be written more concisely as
597 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
599 /// Can be written as
602 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
606 "using combination of `filter_map` and `next` which can usually be written as a single method call"
609 declare_clippy_lint! {
611 /// Checks for usage of `flat_map(|x| x)`.
613 /// ### Why is this bad?
614 /// Readability, this can be written more concisely by using `flatten`.
618 /// # let iter = vec![vec![0]].into_iter();
619 /// iter.flat_map(|x| x);
621 /// Can be written as
623 /// # let iter = vec![vec![0]].into_iter();
626 pub FLAT_MAP_IDENTITY,
628 "call to `flat_map` where `flatten` is sufficient"
631 declare_clippy_lint! {
633 /// Checks for an iterator or string search (such as `find()`,
634 /// `position()`, or `rposition()`) followed by a call to `is_some()` or `is_none()`.
636 /// ### Why is this bad?
637 /// Readability, this can be written more concisely as:
638 /// * `_.any(_)`, or `_.contains(_)` for `is_some()`,
639 /// * `!_.any(_)`, or `!_.contains(_)` for `is_none()`.
643 /// let vec = vec![1];
644 /// vec.iter().find(|x| **x == 0).is_some();
646 /// let _ = "hello world".find("world").is_none();
648 /// Could be written as
650 /// let vec = vec![1];
651 /// vec.iter().any(|x| *x == 0);
653 /// let _ = !"hello world".contains("world");
657 "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()`)"
660 declare_clippy_lint! {
662 /// Checks for usage of `.chars().next()` on a `str` to check
663 /// if it starts with a given char.
665 /// ### Why is this bad?
666 /// Readability, this can be written more concisely as
667 /// `_.starts_with(_)`.
671 /// let name = "foo";
672 /// if name.chars().next() == Some('_') {};
674 /// Could be written as
676 /// let name = "foo";
677 /// if name.starts_with('_') {};
681 "using `.chars().next()` to check if a string starts with a char"
684 declare_clippy_lint! {
686 /// Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
687 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
688 /// `unwrap_or_default` instead.
690 /// ### Why is this bad?
691 /// The function will always be called and potentially
692 /// allocate an object acting as the default.
694 /// ### Known problems
695 /// If the function has side-effects, not calling it will
696 /// change the semantic of the program, but you shouldn't rely on that anyway.
700 /// # let foo = Some(String::new());
701 /// foo.unwrap_or(String::new());
703 /// this can instead be written:
705 /// # let foo = Some(String::new());
706 /// foo.unwrap_or_else(String::new);
710 /// # let foo = Some(String::new());
711 /// foo.unwrap_or_default();
715 "using any `*or` method with a function call, which suggests `*or_else`"
718 declare_clippy_lint! {
720 /// Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
721 /// etc., and suggests to use `unwrap_or_else` instead
723 /// ### Why is this bad?
724 /// The function will always be called.
726 /// ### Known problems
727 /// If the function has side-effects, not calling it will
728 /// change the semantics of the program, but you shouldn't rely on that anyway.
732 /// # let foo = Some(String::new());
733 /// # let err_code = "418";
734 /// # let err_msg = "I'm a teapot";
735 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
739 /// # let foo = Some(String::new());
740 /// # let err_code = "418";
741 /// # let err_msg = "I'm a teapot";
742 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
744 /// this can instead be written:
746 /// # let foo = Some(String::new());
747 /// # let err_code = "418";
748 /// # let err_msg = "I'm a teapot";
749 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
753 "using any `expect` method with a function call"
756 declare_clippy_lint! {
758 /// Checks for usage of `.clone()` on a `Copy` type.
760 /// ### Why is this bad?
761 /// The only reason `Copy` types implement `Clone` is for
762 /// generics, not for using the `clone` method on a concrete type.
770 "using `clone` on a `Copy` type"
773 declare_clippy_lint! {
775 /// Checks for usage of `.clone()` on a ref-counted pointer,
776 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
777 /// function syntax instead (e.g., `Rc::clone(foo)`).
779 /// ### Why is this bad?
780 /// Calling '.clone()' on an Rc, Arc, or Weak
781 /// can obscure the fact that only the pointer is being cloned, not the underlying
786 /// # use std::rc::Rc;
787 /// let x = Rc::new(1);
795 pub CLONE_ON_REF_PTR,
797 "using 'clone' on a ref-counted pointer"
800 declare_clippy_lint! {
802 /// Checks for usage of `.clone()` on an `&&T`.
804 /// ### Why is this bad?
805 /// Cloning an `&&T` copies the inner `&T`, instead of
806 /// cloning the underlying `T`.
813 /// let z = y.clone();
814 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
817 pub CLONE_DOUBLE_REF,
819 "using `clone` on `&&T`"
822 declare_clippy_lint! {
824 /// Checks for usage of `.to_string()` on an `&&T` where
825 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
827 /// ### Why is this bad?
828 /// This bypasses the specialized implementation of
829 /// `ToString` and instead goes through the more expensive string formatting
834 /// // Generic implementation for `T: Display` is used (slow)
835 /// ["foo", "bar"].iter().map(|s| s.to_string());
837 /// // OK, the specialized impl is used
838 /// ["foo", "bar"].iter().map(|&s| s.to_string());
840 pub INEFFICIENT_TO_STRING,
842 "using `to_string` on `&&T` where `T: ToString`"
845 declare_clippy_lint! {
847 /// Checks for `new` not returning a type that contains `Self`.
849 /// ### Why is this bad?
850 /// As a convention, `new` methods are used to make a new
851 /// instance of a type.
854 /// In an impl block:
857 /// # struct NotAFoo;
859 /// fn new() -> NotAFoo {
869 /// // Bad. The type name must contain `Self`
870 /// fn new() -> Bar {
878 /// # struct FooError;
880 /// // Good. Return type contains `Self`
881 /// fn new() -> Result<Foo, FooError> {
887 /// Or in a trait definition:
889 /// pub trait Trait {
890 /// // Bad. The type name must contain `Self`
896 /// pub trait Trait {
897 /// // Good. Return type contains `Self`
898 /// fn new() -> Self;
903 "not returning type containing `Self` in a `new` method"
906 declare_clippy_lint! {
908 /// Checks for string methods that receive a single-character
909 /// `str` as an argument, e.g., `_.split("x")`.
911 /// ### Why is this bad?
912 /// Performing these methods using a `char` is faster than
915 /// ### Known problems
916 /// Does not catch multi-byte unicode characters.
925 pub SINGLE_CHAR_PATTERN,
927 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
930 declare_clippy_lint! {
932 /// Checks for calling `.step_by(0)` on iterators which panics.
934 /// ### Why is this bad?
935 /// This very much looks like an oversight. Use `panic!()` instead if you
936 /// actually intend to panic.
939 /// ```rust,should_panic
940 /// for x in (0..100).step_by(0) {
944 pub ITERATOR_STEP_BY_ZERO,
946 "using `Iterator::step_by(0)`, which will panic at runtime"
949 declare_clippy_lint! {
951 /// Checks for indirect collection of populated `Option`
953 /// ### Why is this bad?
954 /// `Option` is like a collection of 0-1 things, so `flatten`
955 /// automatically does this without suspicious-looking `unwrap` calls.
959 /// let _ = std::iter::empty::<Option<i32>>().filter(Option::is_some).map(Option::unwrap);
963 /// let _ = std::iter::empty::<Option<i32>>().flatten();
965 pub OPTION_FILTER_MAP,
967 "filtering `Option` for `Some` then force-unwrapping, which can be one type-safe operation"
970 declare_clippy_lint! {
972 /// Checks for the use of `iter.nth(0)`.
974 /// ### Why is this bad?
975 /// `iter.next()` is equivalent to
976 /// `iter.nth(0)`, as they both consume the next element,
977 /// but is more readable.
981 /// # use std::collections::HashSet;
983 /// # let mut s = HashSet::new();
985 /// let x = s.iter().nth(0);
988 /// # let mut s = HashSet::new();
990 /// let x = s.iter().next();
994 "replace `iter.nth(0)` with `iter.next()`"
997 declare_clippy_lint! {
999 /// Checks for use of `.iter().nth()` (and the related
1000 /// `.iter_mut().nth()`) on standard library types with *O*(1) element access.
1002 /// ### Why is this bad?
1003 /// `.get()` and `.get_mut()` are more efficient and more
1008 /// let some_vec = vec![0, 1, 2, 3];
1009 /// let bad_vec = some_vec.iter().nth(3);
1010 /// let bad_slice = &some_vec[..].iter().nth(3);
1012 /// The correct use would be:
1014 /// let some_vec = vec![0, 1, 2, 3];
1015 /// let bad_vec = some_vec.get(3);
1016 /// let bad_slice = &some_vec[..].get(3);
1020 "using `.iter().nth()` on a standard library type with O(1) element access"
1023 declare_clippy_lint! {
1024 /// ### What it does
1025 /// Checks for use of `.skip(x).next()` on iterators.
1027 /// ### Why is this bad?
1028 /// `.nth(x)` is cleaner
1032 /// let some_vec = vec![0, 1, 2, 3];
1033 /// let bad_vec = some_vec.iter().skip(3).next();
1034 /// let bad_slice = &some_vec[..].iter().skip(3).next();
1036 /// The correct use would be:
1038 /// let some_vec = vec![0, 1, 2, 3];
1039 /// let bad_vec = some_vec.iter().nth(3);
1040 /// let bad_slice = &some_vec[..].iter().nth(3);
1044 "using `.skip(x).next()` on an iterator"
1047 declare_clippy_lint! {
1048 /// ### What it does
1049 /// Checks for use of `.get().unwrap()` (or
1050 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
1052 /// ### Why is this bad?
1053 /// Using the Index trait (`[]`) is more clear and more
1056 /// ### Known problems
1057 /// Not a replacement for error handling: Using either
1058 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
1059 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
1060 /// temporary placeholder for dealing with the `Option` type, then this does
1061 /// not mitigate the need for error handling. If there is a chance that `.get()`
1062 /// will be `None` in your program, then it is advisable that the `None` case
1063 /// is handled in a future refactor instead of using `.unwrap()` or the Index
1068 /// let mut some_vec = vec![0, 1, 2, 3];
1069 /// let last = some_vec.get(3).unwrap();
1070 /// *some_vec.get_mut(0).unwrap() = 1;
1072 /// The correct use would be:
1074 /// let mut some_vec = vec![0, 1, 2, 3];
1075 /// let last = some_vec[3];
1076 /// some_vec[0] = 1;
1080 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
1083 declare_clippy_lint! {
1084 /// ### What it does
1085 /// Checks for occurrences where one vector gets extended instead of append
1087 /// ### Why is this bad?
1088 /// Using `append` instead of `extend` is more concise and faster
1092 /// let mut a = vec![1, 2, 3];
1093 /// let mut b = vec![4, 5, 6];
1096 /// a.extend(b.drain(..));
1099 /// a.append(&mut b);
1101 pub EXTEND_WITH_DRAIN,
1103 "using vec.append(&mut vec) to move the full range of a vecor to another"
1106 declare_clippy_lint! {
1107 /// ### What it does
1108 /// Checks for the use of `.extend(s.chars())` where s is a
1109 /// `&str` or `String`.
1111 /// ### Why is this bad?
1112 /// `.push_str(s)` is clearer
1116 /// let abc = "abc";
1117 /// let def = String::from("def");
1118 /// let mut s = String::new();
1119 /// s.extend(abc.chars());
1120 /// s.extend(def.chars());
1122 /// The correct use would be:
1124 /// let abc = "abc";
1125 /// let def = String::from("def");
1126 /// let mut s = String::new();
1127 /// s.push_str(abc);
1128 /// s.push_str(&def);
1130 pub STRING_EXTEND_CHARS,
1132 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1135 declare_clippy_lint! {
1136 /// ### What it does
1137 /// Checks for the use of `.cloned().collect()` on slice to
1140 /// ### Why is this bad?
1141 /// `.to_vec()` is clearer
1145 /// let s = [1, 2, 3, 4, 5];
1146 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1148 /// The better use would be:
1150 /// let s = [1, 2, 3, 4, 5];
1151 /// let s2: Vec<isize> = s.to_vec();
1153 pub ITER_CLONED_COLLECT,
1155 "using `.cloned().collect()` on slice to create a `Vec`"
1158 declare_clippy_lint! {
1159 /// ### What it does
1160 /// Checks for usage of `_.chars().last()` or
1161 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1163 /// ### Why is this bad?
1164 /// Readability, this can be written more concisely as
1165 /// `_.ends_with(_)`.
1169 /// # let name = "_";
1172 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1175 /// name.ends_with('_') || name.ends_with('-');
1179 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1182 declare_clippy_lint! {
1183 /// ### What it does
1184 /// Checks for usage of `.as_ref()` or `.as_mut()` where the
1185 /// types before and after the call are the same.
1187 /// ### Why is this bad?
1188 /// The call is unnecessary.
1192 /// # fn do_stuff(x: &[i32]) {}
1193 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1194 /// do_stuff(x.as_ref());
1196 /// The correct use would be:
1198 /// # fn do_stuff(x: &[i32]) {}
1199 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1204 "using `as_ref` where the types before and after the call are the same"
1207 declare_clippy_lint! {
1208 /// ### What it does
1209 /// Checks for using `fold` when a more succinct alternative exists.
1210 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1211 /// `sum` or `product`.
1213 /// ### Why is this bad?
1218 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1220 /// This could be written as:
1222 /// let _ = (0..3).any(|x| x > 2);
1224 pub UNNECESSARY_FOLD,
1226 "using `fold` when a more succinct alternative exists"
1229 declare_clippy_lint! {
1230 /// ### What it does
1231 /// Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1232 /// More specifically it checks if the closure provided is only performing one of the
1233 /// filter or map operations and suggests the appropriate option.
1235 /// ### Why is this bad?
1236 /// Complexity. The intent is also clearer if only a single
1237 /// operation is being performed.
1241 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1243 /// // As there is no transformation of the argument this could be written as:
1244 /// let _ = (0..3).filter(|&x| x > 2);
1248 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1250 /// // As there is no conditional check on the argument this could be written as:
1251 /// let _ = (0..4).map(|x| x + 1);
1253 pub UNNECESSARY_FILTER_MAP,
1255 "using `filter_map` when a more succinct alternative exists"
1258 declare_clippy_lint! {
1259 /// ### What it does
1260 /// Checks for `into_iter` calls on references which should be replaced by `iter`
1263 /// ### Why is this bad?
1264 /// Readability. Calling `into_iter` on a reference will not move out its
1265 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1266 /// `iter_mut` directly.
1271 /// let _ = (&vec![3, 4, 5]).into_iter();
1274 /// let _ = (&vec![3, 4, 5]).iter();
1276 pub INTO_ITER_ON_REF,
1278 "using `.into_iter()` on a reference"
1281 declare_clippy_lint! {
1282 /// ### What it does
1283 /// Checks for calls to `map` followed by a `count`.
1285 /// ### Why is this bad?
1286 /// It looks suspicious. Maybe `map` was confused with `filter`.
1287 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1288 /// drive the iterator to completion, you can just use `for_each` instead.
1292 /// let _ = (0..3).map(|x| x + 2).count();
1296 "suspicious usage of map"
1299 declare_clippy_lint! {
1300 /// ### What it does
1301 /// Checks for `MaybeUninit::uninit().assume_init()`.
1303 /// ### Why is this bad?
1304 /// For most types, this is undefined behavior.
1306 /// ### Known problems
1307 /// For now, we accept empty tuples and tuples / arrays
1308 /// of `MaybeUninit`. There may be other types that allow uninitialized
1309 /// data, but those are not yet rigorously defined.
1313 /// // Beware the UB
1314 /// use std::mem::MaybeUninit;
1316 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1319 /// Note that the following is OK:
1322 /// use std::mem::MaybeUninit;
1324 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1325 /// MaybeUninit::uninit().assume_init()
1328 pub UNINIT_ASSUMED_INIT,
1330 "`MaybeUninit::uninit().assume_init()`"
1333 declare_clippy_lint! {
1334 /// ### What it does
1335 /// Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1337 /// ### Why is this bad?
1338 /// These can be written simply with `saturating_add/sub` methods.
1342 /// # let y: u32 = 0;
1343 /// # let x: u32 = 100;
1344 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1345 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1348 /// can be written using dedicated methods for saturating addition/subtraction as:
1351 /// # let y: u32 = 0;
1352 /// # let x: u32 = 100;
1353 /// let add = x.saturating_add(y);
1354 /// let sub = x.saturating_sub(y);
1356 pub MANUAL_SATURATING_ARITHMETIC,
1358 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1361 declare_clippy_lint! {
1362 /// ### What it does
1363 /// Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1364 /// zero-sized types
1366 /// ### Why is this bad?
1367 /// This is a no-op, and likely unintended
1371 /// unsafe { (&() as *const ()).offset(1) };
1375 "Check for offset calculations on raw pointers to zero-sized types"
1378 declare_clippy_lint! {
1379 /// ### What it does
1380 /// Checks for `FileType::is_file()`.
1382 /// ### Why is this bad?
1383 /// When people testing a file type with `FileType::is_file`
1384 /// they are testing whether a path is something they can get bytes from. But
1385 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1386 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1391 /// let metadata = std::fs::metadata("foo.txt")?;
1392 /// let filetype = metadata.file_type();
1394 /// if filetype.is_file() {
1397 /// # Ok::<_, std::io::Error>(())
1401 /// should be written as:
1405 /// let metadata = std::fs::metadata("foo.txt")?;
1406 /// let filetype = metadata.file_type();
1408 /// if !filetype.is_dir() {
1411 /// # Ok::<_, std::io::Error>(())
1414 pub FILETYPE_IS_FILE,
1416 "`FileType::is_file` is not recommended to test for readable file type"
1419 declare_clippy_lint! {
1420 /// ### What it does
1421 /// Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1423 /// ### Why is this bad?
1424 /// Readability, this can be written more concisely as
1429 /// # let opt = Some("".to_string());
1430 /// opt.as_ref().map(String::as_str)
1433 /// Can be written as
1435 /// # let opt = Some("".to_string());
1439 pub OPTION_AS_REF_DEREF,
1441 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1444 declare_clippy_lint! {
1445 /// ### What it does
1446 /// Checks for usage of `iter().next()` on a Slice or an Array
1448 /// ### Why is this bad?
1449 /// These can be shortened into `.get()`
1453 /// # let a = [1, 2, 3];
1454 /// # let b = vec![1, 2, 3];
1455 /// a[2..].iter().next();
1456 /// b.iter().next();
1458 /// should be written as:
1460 /// # let a = [1, 2, 3];
1461 /// # let b = vec![1, 2, 3];
1465 pub ITER_NEXT_SLICE,
1467 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1470 declare_clippy_lint! {
1471 /// ### What it does
1472 /// Warns when using `push_str`/`insert_str` with a single-character string literal
1473 /// where `push`/`insert` with a `char` would work fine.
1475 /// ### Why is this bad?
1476 /// It's less clear that we are pushing a single character.
1480 /// let mut string = String::new();
1481 /// string.insert_str(0, "R");
1482 /// string.push_str("R");
1484 /// Could be written as
1486 /// let mut string = String::new();
1487 /// string.insert(0, 'R');
1488 /// string.push('R');
1490 pub SINGLE_CHAR_ADD_STR,
1492 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1495 declare_clippy_lint! {
1496 /// ### What it does
1497 /// As the counterpart to `or_fun_call`, this lint looks for unnecessary
1498 /// lazily evaluated closures on `Option` and `Result`.
1500 /// This lint suggests changing the following functions, when eager evaluation results in
1502 /// - `unwrap_or_else` to `unwrap_or`
1503 /// - `and_then` to `and`
1504 /// - `or_else` to `or`
1505 /// - `get_or_insert_with` to `get_or_insert`
1506 /// - `ok_or_else` to `ok_or`
1508 /// ### Why is this bad?
1509 /// Using eager evaluation is shorter and simpler in some cases.
1511 /// ### Known problems
1512 /// It is possible, but not recommended for `Deref` and `Index` to have
1513 /// side effects. Eagerly evaluating them can change the semantics of the program.
1517 /// // example code where clippy issues a warning
1518 /// let opt: Option<u32> = None;
1520 /// opt.unwrap_or_else(|| 42);
1524 /// let opt: Option<u32> = None;
1526 /// opt.unwrap_or(42);
1528 pub UNNECESSARY_LAZY_EVALUATIONS,
1530 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1533 declare_clippy_lint! {
1534 /// ### What it does
1535 /// Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1537 /// ### Why is this bad?
1538 /// Using `try_for_each` instead is more readable and idiomatic.
1542 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1546 /// (0..3).try_for_each(|t| Err(t));
1548 pub MAP_COLLECT_RESULT_UNIT,
1550 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1553 declare_clippy_lint! {
1554 /// ### What it does
1555 /// Checks for `from_iter()` function calls on types that implement the `FromIterator`
1558 /// ### Why is this bad?
1559 /// It is recommended style to use collect. See
1560 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1564 /// use std::iter::FromIterator;
1566 /// let five_fives = std::iter::repeat(5).take(5);
1568 /// let v = Vec::from_iter(five_fives);
1570 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1574 /// let five_fives = std::iter::repeat(5).take(5);
1576 /// let v: Vec<i32> = five_fives.collect();
1578 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1580 pub FROM_ITER_INSTEAD_OF_COLLECT,
1582 "use `.collect()` instead of `::from_iter()`"
1585 declare_clippy_lint! {
1586 /// ### What it does
1587 /// Checks for usage of `inspect().for_each()`.
1589 /// ### Why is this bad?
1590 /// It is the same as performing the computation
1591 /// inside `inspect` at the beginning of the closure in `for_each`.
1595 /// [1,2,3,4,5].iter()
1596 /// .inspect(|&x| println!("inspect the number: {}", x))
1597 /// .for_each(|&x| {
1598 /// assert!(x >= 0);
1601 /// Can be written as
1603 /// [1,2,3,4,5].iter()
1604 /// .for_each(|&x| {
1605 /// println!("inspect the number: {}", x);
1606 /// assert!(x >= 0);
1609 pub INSPECT_FOR_EACH,
1611 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1614 declare_clippy_lint! {
1615 /// ### What it does
1616 /// Checks for usage of `filter_map(|x| x)`.
1618 /// ### Why is this bad?
1619 /// Readability, this can be written more concisely by using `flatten`.
1623 /// # let iter = vec![Some(1)].into_iter();
1624 /// iter.filter_map(|x| x);
1628 /// # let iter = vec![Some(1)].into_iter();
1631 pub FILTER_MAP_IDENTITY,
1633 "call to `filter_map` where `flatten` is sufficient"
1636 declare_clippy_lint! {
1637 /// ### What it does
1638 /// Checks for instances of `map(f)` where `f` is the identity function.
1640 /// ### Why is this bad?
1641 /// It can be written more concisely without the call to `map`.
1645 /// let x = [1, 2, 3];
1646 /// let y: Vec<_> = x.iter().map(|x| x).map(|x| 2*x).collect();
1650 /// let x = [1, 2, 3];
1651 /// let y: Vec<_> = x.iter().map(|x| 2*x).collect();
1655 "using iterator.map(|x| x)"
1658 declare_clippy_lint! {
1659 /// ### What it does
1660 /// Checks for the use of `.bytes().nth()`.
1662 /// ### Why is this bad?
1663 /// `.as_bytes().get()` is more efficient and more
1669 /// let _ = "Hello".bytes().nth(3);
1672 /// let _ = "Hello".as_bytes().get(3);
1676 "replace `.bytes().nth()` with `.as_bytes().get()`"
1679 declare_clippy_lint! {
1680 /// ### What it does
1681 /// Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1683 /// ### Why is this bad?
1684 /// These methods do the same thing as `_.clone()` but may be confusing as
1685 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1689 /// let a = vec![1, 2, 3];
1690 /// let b = a.to_vec();
1691 /// let c = a.to_owned();
1695 /// let a = vec![1, 2, 3];
1696 /// let b = a.clone();
1697 /// let c = a.clone();
1701 "implicitly cloning a value by invoking a function on its dereferenced type"
1704 declare_clippy_lint! {
1705 /// ### What it does
1706 /// Checks for the use of `.iter().count()`.
1708 /// ### Why is this bad?
1709 /// `.len()` is more efficient and more
1715 /// let some_vec = vec![0, 1, 2, 3];
1716 /// let _ = some_vec.iter().count();
1717 /// let _ = &some_vec[..].iter().count();
1720 /// let some_vec = vec![0, 1, 2, 3];
1721 /// let _ = some_vec.len();
1722 /// let _ = &some_vec[..].len();
1726 "replace `.iter().count()` with `.len()`"
1729 declare_clippy_lint! {
1730 /// ### What it does
1731 /// Checks for calls to [`splitn`]
1732 /// (https://doc.rust-lang.org/std/primitive.str.html#method.splitn) and
1733 /// related functions with either zero or one splits.
1735 /// ### Why is this bad?
1736 /// These calls don't actually split the value and are
1737 /// likely to be intended as a different number.
1743 /// for x in s.splitn(1, ":") {
1749 /// for x in s.splitn(2, ":") {
1753 pub SUSPICIOUS_SPLITN,
1755 "checks for `.splitn(0, ..)` and `.splitn(1, ..)`"
1758 declare_clippy_lint! {
1759 /// ### What it does
1760 /// Checks for manual implementations of `str::repeat`
1762 /// ### Why is this bad?
1763 /// These are both harder to read, as well as less performant.
1768 /// let x: String = std::iter::repeat('x').take(10).collect();
1771 /// let x: String = "x".repeat(10);
1773 pub MANUAL_STR_REPEAT,
1775 "manual implementation of `str::repeat`"
1778 declare_clippy_lint! {
1779 /// **What it does:** Checks for usages of `str::splitn(2, _)`
1781 /// **Why is this bad?** `split_once` is both clearer in intent and slightly more efficient.
1783 /// **Known problems:** None.
1789 /// let (key, value) = _.splitn(2, '=').next_tuple()?;
1790 /// let value = _.splitn(2, '=').nth(1)?;
1793 /// let (key, value) = _.split_once('=')?;
1794 /// let value = _.split_once('=')?.1;
1796 pub MANUAL_SPLIT_ONCE,
1798 "replace `.splitn(2, pat)` with `.split_once(pat)`"
1801 pub struct Methods {
1802 avoid_breaking_exported_api: bool,
1803 msrv: Option<RustcVersion>,
1808 pub fn new(avoid_breaking_exported_api: bool, msrv: Option<RustcVersion>) -> Self {
1810 avoid_breaking_exported_api,
1816 impl_lint_pass!(Methods => [
1819 SHOULD_IMPLEMENT_TRAIT,
1820 WRONG_SELF_CONVENTION,
1822 UNWRAP_OR_ELSE_DEFAULT,
1824 RESULT_MAP_OR_INTO_OPTION,
1826 BIND_INSTEAD_OF_MAP,
1834 CLONED_INSTEAD_OF_COPIED,
1836 INEFFICIENT_TO_STRING,
1838 SINGLE_CHAR_PATTERN,
1839 SINGLE_CHAR_ADD_STR,
1843 FILTER_MAP_IDENTITY,
1851 ITERATOR_STEP_BY_ZERO,
1859 STRING_EXTEND_CHARS,
1860 ITER_CLONED_COLLECT,
1863 UNNECESSARY_FILTER_MAP,
1866 UNINIT_ASSUMED_INIT,
1867 MANUAL_SATURATING_ARITHMETIC,
1870 OPTION_AS_REF_DEREF,
1871 UNNECESSARY_LAZY_EVALUATIONS,
1872 MAP_COLLECT_RESULT_UNIT,
1873 FROM_ITER_INSTEAD_OF_COLLECT,
1882 /// Extracts a method call name, args, and `Span` of the method name.
1883 fn method_call<'tcx>(recv: &'tcx hir::Expr<'tcx>) -> Option<(SymbolStr, &'tcx [hir::Expr<'tcx>], Span)> {
1884 if let ExprKind::MethodCall(path, span, args, _) = recv.kind {
1885 if !args.iter().any(|e| e.span.from_expansion()) {
1886 return Some((path.ident.name.as_str(), args, span));
1892 /// Same as `method_call` but the `SymbolStr` is dereferenced into a temporary `&str`
1893 macro_rules! method_call {
1897 .map(|&(ref name, args, span)| (&**name, args, span))
1901 impl<'tcx> LateLintPass<'tcx> for Methods {
1902 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1903 if in_macro(expr.span) {
1907 check_methods(cx, expr, self.msrv.as_ref());
1910 hir::ExprKind::Call(func, args) => {
1911 from_iter_instead_of_collect::check(cx, expr, args, func);
1913 hir::ExprKind::MethodCall(method_call, ref method_span, args, _) => {
1914 or_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1915 expect_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1916 clone_on_copy::check(cx, expr, method_call.ident.name, args);
1917 clone_on_ref_ptr::check(cx, expr, method_call.ident.name, args);
1918 inefficient_to_string::check(cx, expr, method_call.ident.name, args);
1919 single_char_add_str::check(cx, expr, args);
1920 into_iter_on_ref::check(cx, expr, *method_span, method_call.ident.name, args);
1921 single_char_pattern::check(cx, expr, method_call.ident.name, args);
1923 hir::ExprKind::Binary(op, lhs, rhs) if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne => {
1924 let mut info = BinaryExprInfo {
1928 eq: op.node == hir::BinOpKind::Eq,
1930 lint_binary_expr_with_method_call(cx, &mut info);
1936 #[allow(clippy::too_many_lines)]
1937 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1938 if in_external_macro(cx.sess(), impl_item.span) {
1941 let name = impl_item.ident.name.as_str();
1942 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
1943 let item = cx.tcx.hir().expect_item(parent);
1944 let self_ty = cx.tcx.type_of(item.def_id);
1946 let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }));
1948 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1949 if let Some(first_arg) = iter_input_pats(sig.decl, cx.tcx.hir().body(id)).next();
1951 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
1952 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1954 let first_arg_ty = &method_sig.inputs().iter().next();
1956 // check conventions w.r.t. conversion method names and predicates
1957 if let Some(first_arg_ty) = first_arg_ty;
1960 // if this impl block implements a trait, lint in trait definition instead
1961 if !implements_trait && cx.access_levels.is_exported(impl_item.def_id) {
1962 // check missing trait implementations
1963 for method_config in &TRAIT_METHODS {
1964 if name == method_config.method_name &&
1965 sig.decl.inputs.len() == method_config.param_count &&
1966 method_config.output_type.matches(&sig.decl.output) &&
1967 method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1968 fn_header_equals(method_config.fn_header, sig.header) &&
1969 method_config.lifetime_param_cond(impl_item)
1973 SHOULD_IMPLEMENT_TRAIT,
1976 "method `{}` can be confused for the standard trait method `{}::{}`",
1977 method_config.method_name,
1978 method_config.trait_name,
1979 method_config.method_name
1983 "consider implementing the trait `{}` or choosing a less ambiguous method name",
1984 method_config.trait_name
1991 if sig.decl.implicit_self.has_implicit_self()
1992 && !(self.avoid_breaking_exported_api
1993 && cx.access_levels.is_exported(impl_item.def_id))
1995 wrong_self_convention::check(
2008 // if this impl block implements a trait, lint in trait definition instead
2009 if implements_trait {
2013 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
2014 let ret_ty = return_ty(cx, impl_item.hir_id());
2016 // walk the return type and check for Self (this does not check associated types)
2017 if let Some(self_adt) = self_ty.ty_adt_def() {
2018 if contains_adt_constructor(cx.tcx, ret_ty, self_adt) {
2021 } else if contains_ty(cx.tcx, ret_ty, self_ty) {
2025 // if return type is impl trait, check the associated types
2026 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
2027 // one of the associated types must be Self
2028 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
2029 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
2030 // walk the associated type and check for Self
2031 if let Some(self_adt) = self_ty.ty_adt_def() {
2032 if contains_adt_constructor(cx.tcx, projection_predicate.ty, self_adt) {
2035 } else if contains_ty(cx.tcx, projection_predicate.ty, self_ty) {
2042 if name == "new" && !TyS::same_type(ret_ty, self_ty) {
2047 "methods called `new` usually return `Self`",
2053 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
2054 if in_external_macro(cx.tcx.sess, item.span) {
2059 if let TraitItemKind::Fn(ref sig, _) = item.kind;
2060 if sig.decl.implicit_self.has_implicit_self();
2061 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
2064 let first_arg_span = first_arg_ty.span;
2065 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
2066 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2067 wrong_self_convention::check(
2069 &item.ident.name.as_str(),
2080 if item.ident.name == sym::new;
2081 if let TraitItemKind::Fn(_, _) = item.kind;
2082 let ret_ty = return_ty(cx, item.hir_id());
2083 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty().skip_binder();
2084 if !contains_ty(cx.tcx, ret_ty, self_ty);
2091 "methods called `new` usually return `Self`",
2097 extract_msrv_attr!(LateContext);
2100 #[allow(clippy::too_many_lines)]
2101 fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Option<&RustcVersion>) {
2102 if let Some((name, [recv, args @ ..], span)) = method_call!(expr) {
2103 match (name, args) {
2104 ("add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub", [_arg]) => {
2105 zst_offset::check(cx, expr, recv);
2107 ("and_then", [arg]) => {
2108 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, recv, arg);
2109 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, recv, arg);
2110 if !biom_option_linted && !biom_result_linted {
2111 unnecessary_lazy_eval::check(cx, expr, recv, arg, "and");
2114 ("as_mut", []) => useless_asref::check(cx, expr, "as_mut", recv),
2115 ("as_ref", []) => useless_asref::check(cx, expr, "as_ref", recv),
2116 ("assume_init", []) => uninit_assumed_init::check(cx, expr, recv),
2117 ("cloned", []) => cloned_instead_of_copied::check(cx, expr, recv, span, msrv),
2118 ("collect", []) => match method_call!(recv) {
2119 Some(("cloned", [recv2], _)) => iter_cloned_collect::check(cx, expr, recv2),
2120 Some(("map", [m_recv, m_arg], _)) => {
2121 map_collect_result_unit::check(cx, expr, m_recv, m_arg, recv);
2123 Some(("take", [take_self_arg, take_arg], _)) => {
2124 if meets_msrv(msrv, &msrvs::STR_REPEAT) {
2125 manual_str_repeat::check(cx, expr, recv, take_self_arg, take_arg);
2130 ("count", []) => match method_call!(recv) {
2131 Some((name @ ("into_iter" | "iter" | "iter_mut"), [recv2], _)) => {
2132 iter_count::check(cx, expr, recv2, name);
2134 Some(("map", [_, arg], _)) => suspicious_map::check(cx, expr, recv, arg),
2137 ("expect", [_]) => match method_call!(recv) {
2138 Some(("ok", [recv], _)) => ok_expect::check(cx, expr, recv),
2139 _ => expect_used::check(cx, expr, recv),
2141 ("extend", [arg]) => {
2142 string_extend_chars::check(cx, expr, recv, arg);
2143 extend_with_drain::check(cx, expr, recv, arg);
2145 ("filter_map", [arg]) => {
2146 unnecessary_filter_map::check(cx, expr, arg);
2147 filter_map_identity::check(cx, expr, arg, span);
2149 ("flat_map", [arg]) => {
2150 flat_map_identity::check(cx, expr, arg, span);
2151 flat_map_option::check(cx, expr, arg, span);
2153 ("flatten", []) => {
2154 if let Some(("map", [recv, map_arg], _)) = method_call!(recv) {
2155 map_flatten::check(cx, expr, recv, map_arg);
2158 ("fold", [init, acc]) => unnecessary_fold::check(cx, expr, init, acc, span),
2159 ("for_each", [_]) => {
2160 if let Some(("inspect", [_, _], span2)) = method_call!(recv) {
2161 inspect_for_each::check(cx, expr, span2);
2164 ("get_or_insert_with", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "get_or_insert"),
2165 ("is_file", []) => filetype_is_file::check(cx, expr, recv),
2166 ("is_none", []) => check_is_some_is_none(cx, expr, recv, false),
2167 ("is_some", []) => check_is_some_is_none(cx, expr, recv, true),
2168 ("map", [m_arg]) => {
2169 if let Some((name, [recv2, args @ ..], span2)) = method_call!(recv) {
2170 match (name, args) {
2171 ("as_mut", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, true, msrv),
2172 ("as_ref", []) => option_as_ref_deref::check(cx, expr, recv2, m_arg, false, msrv),
2173 ("filter", [f_arg]) => {
2174 filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, false);
2176 ("find", [f_arg]) => filter_map::check(cx, expr, recv2, f_arg, span2, recv, m_arg, span, true),
2180 map_identity::check(cx, expr, recv, m_arg, span);
2182 ("map_or", [def, map]) => option_map_or_none::check(cx, expr, recv, def, map),
2184 if let Some((name, [recv, args @ ..], _)) = method_call!(recv) {
2185 match (name, args) {
2186 ("filter", [arg]) => filter_next::check(cx, expr, recv, arg),
2187 ("filter_map", [arg]) => filter_map_next::check(cx, expr, recv, arg, msrv),
2188 ("iter", []) => iter_next_slice::check(cx, expr, recv),
2189 ("skip", [arg]) => iter_skip_next::check(cx, expr, recv, arg),
2190 ("skip_while", [_]) => skip_while_next::check(cx, expr),
2195 ("nth", [n_arg]) => match method_call!(recv) {
2196 Some(("bytes", [recv2], _)) => bytes_nth::check(cx, expr, recv2, n_arg),
2197 Some(("iter", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, false),
2198 Some(("iter_mut", [recv2], _)) => iter_nth::check(cx, expr, recv2, recv, n_arg, true),
2199 _ => iter_nth_zero::check(cx, expr, recv, n_arg),
2201 ("ok_or_else", [arg]) => unnecessary_lazy_eval::check(cx, expr, recv, arg, "ok_or"),
2202 ("or_else", [arg]) => {
2203 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, recv, arg) {
2204 unnecessary_lazy_eval::check(cx, expr, recv, arg, "or");
2207 ("splitn" | "rsplitn", [count_arg, pat_arg]) => {
2208 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2209 suspicious_splitn::check(cx, name, expr, recv, count);
2210 if count == 2 && meets_msrv(msrv, &msrvs::STR_SPLIT_ONCE) {
2211 manual_split_once::check(cx, name, expr, recv, pat_arg);
2215 ("splitn_mut" | "rsplitn_mut", [count_arg, _]) => {
2216 if let Some((Constant::Int(count), _)) = constant(cx, cx.typeck_results(), count_arg) {
2217 suspicious_splitn::check(cx, name, expr, recv, count);
2220 ("step_by", [arg]) => iterator_step_by_zero::check(cx, expr, arg),
2221 ("to_os_string" | "to_owned" | "to_path_buf" | "to_vec", []) => {
2222 implicit_clone::check(cx, name, expr, recv, span);
2224 ("unwrap", []) => match method_call!(recv) {
2225 Some(("get", [recv, get_arg], _)) => get_unwrap::check(cx, expr, recv, get_arg, false),
2226 Some(("get_mut", [recv, get_arg], _)) => get_unwrap::check(cx, expr, recv, get_arg, true),
2227 _ => unwrap_used::check(cx, expr, recv),
2229 ("unwrap_or", [u_arg]) => match method_call!(recv) {
2230 Some((arith @ ("checked_add" | "checked_sub" | "checked_mul"), [lhs, rhs], _)) => {
2231 manual_saturating_arithmetic::check(cx, expr, lhs, rhs, u_arg, &arith["checked_".len()..]);
2233 Some(("map", [m_recv, m_arg], span)) => {
2234 option_map_unwrap_or::check(cx, expr, m_recv, m_arg, recv, u_arg, span);
2238 ("unwrap_or_else", [u_arg]) => match method_call!(recv) {
2239 Some(("map", [recv, map_arg], _)) if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, msrv) => {},
2241 unwrap_or_else_default::check(cx, expr, recv, u_arg);
2242 unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2250 fn check_is_some_is_none(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, is_some: bool) {
2251 if let Some((name @ ("find" | "position" | "rposition"), [f_recv, arg], span)) = method_call!(recv) {
2252 search_is_some::check(cx, expr, name, is_some, f_recv, arg, recv, span);
2256 /// Used for `lint_binary_expr_with_method_call`.
2257 #[derive(Copy, Clone)]
2258 struct BinaryExprInfo<'a> {
2259 expr: &'a hir::Expr<'a>,
2260 chain: &'a hir::Expr<'a>,
2261 other: &'a hir::Expr<'a>,
2265 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2266 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2267 macro_rules! lint_with_both_lhs_and_rhs {
2268 ($func:expr, $cx:expr, $info:ident) => {
2269 if !$func($cx, $info) {
2270 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2271 if $func($cx, $info) {
2278 lint_with_both_lhs_and_rhs!(chars_next_cmp::check, cx, info);
2279 lint_with_both_lhs_and_rhs!(chars_last_cmp::check, cx, info);
2280 lint_with_both_lhs_and_rhs!(chars_next_cmp_with_unwrap::check, cx, info);
2281 lint_with_both_lhs_and_rhs!(chars_last_cmp_with_unwrap::check, cx, info);
2284 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2285 unsafety: hir::Unsafety::Normal,
2286 constness: hir::Constness::NotConst,
2287 asyncness: hir::IsAsync::NotAsync,
2288 abi: rustc_target::spec::abi::Abi::Rust,
2291 struct ShouldImplTraitCase {
2292 trait_name: &'static str,
2293 method_name: &'static str,
2295 fn_header: hir::FnHeader,
2296 // implicit self kind expected (none, self, &self, ...)
2297 self_kind: SelfKind,
2298 // checks against the output type
2299 output_type: OutType,
2300 // certain methods with explicit lifetimes can't implement the equivalent trait method
2301 lint_explicit_lifetime: bool,
2303 impl ShouldImplTraitCase {
2305 trait_name: &'static str,
2306 method_name: &'static str,
2308 fn_header: hir::FnHeader,
2309 self_kind: SelfKind,
2310 output_type: OutType,
2311 lint_explicit_lifetime: bool,
2312 ) -> ShouldImplTraitCase {
2313 ShouldImplTraitCase {
2320 lint_explicit_lifetime,
2324 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2325 self.lint_explicit_lifetime
2326 || !impl_item.generics.params.iter().any(|p| {
2329 hir::GenericParamKind::Lifetime {
2330 kind: hir::LifetimeParamKind::Explicit
2338 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2339 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2340 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2341 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2342 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2343 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2344 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2345 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2346 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2347 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2348 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2349 // FIXME: default doesn't work
2350 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2351 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2352 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2353 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2354 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2355 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2356 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2357 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2358 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2359 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2360 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2361 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2362 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2363 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2364 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2365 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2366 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2367 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2368 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2369 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2372 #[derive(Clone, Copy, PartialEq, Debug)]
2381 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2382 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2383 if ty == parent_ty {
2385 } else if ty.is_box() {
2386 ty.boxed_ty() == parent_ty
2387 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2388 if let ty::Adt(_, substs) = ty.kind() {
2389 substs.types().next().map_or(false, |t| t == parent_ty)
2398 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2399 if let ty::Ref(_, t, m) = *ty.kind() {
2400 return m == mutability && t == parent_ty;
2403 let trait_path = match mutability {
2404 hir::Mutability::Not => &paths::ASREF_TRAIT,
2405 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2408 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2410 None => return false,
2412 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2416 Self::Value => matches_value(cx, parent_ty, ty),
2417 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2418 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2419 Self::No => ty != parent_ty,
2424 fn description(self) -> &'static str {
2426 Self::Value => "`self` by value",
2427 Self::Ref => "`self` by reference",
2428 Self::RefMut => "`self` by mutable reference",
2429 Self::No => "no `self`",
2434 #[derive(Clone, Copy)]
2443 fn matches(self, ty: &hir::FnRetTy<'_>) -> bool {
2444 let is_unit = |ty: &hir::Ty<'_>| matches!(ty.kind, hir::TyKind::Tup(&[]));
2446 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2447 (Self::Unit, &hir::FnRetTy::Return(ty)) if is_unit(ty) => true,
2448 (Self::Bool, &hir::FnRetTy::Return(ty)) if is_bool(ty) => true,
2449 (Self::Any, &hir::FnRetTy::Return(ty)) if !is_unit(ty) => true,
2450 (Self::Ref, &hir::FnRetTy::Return(ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2456 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2457 if let hir::TyKind::Path(QPath::Resolved(_, path)) = ty.kind {
2458 matches!(path.res, Res::PrimTy(PrimTy::Bool))
2464 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2465 expected.constness == actual.constness
2466 && expected.unsafety == actual.unsafety
2467 && expected.asyncness == actual.asyncness