1 mod bind_instead_of_map;
10 mod filter_map_flat_map;
11 mod filter_map_identity;
15 mod flat_map_identity;
16 mod from_iter_instead_of_collect;
19 mod inefficient_to_string;
22 mod iter_cloned_collect;
28 mod iterator_step_by_zero;
29 mod manual_saturating_arithmetic;
30 mod map_collect_result_unit;
34 mod option_as_ref_deref;
35 mod option_map_or_none;
36 mod option_map_unwrap_or;
39 mod single_char_insert_string;
40 mod single_char_pattern;
41 mod single_char_push_string;
43 mod string_extend_chars;
45 mod uninit_assumed_init;
46 mod unnecessary_filter_map;
48 mod unnecessary_lazy_eval;
51 mod wrong_self_convention;
54 use bind_instead_of_map::BindInsteadOfMap;
55 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg};
56 use clippy_utils::source::snippet_with_applicability;
57 use clippy_utils::ty::{contains_ty, implements_trait, is_copy, is_type_diagnostic_item};
59 contains_return, get_trait_def_id, in_macro, iter_input_pats, match_def_path, match_qpath, method_calls,
60 method_chain_args, paths, return_ty, single_segment_path, SpanlessEq,
62 use if_chain::if_chain;
64 use rustc_errors::Applicability;
66 use rustc_hir::{TraitItem, TraitItemKind};
67 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
68 use rustc_middle::lint::in_external_macro;
69 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
70 use rustc_semver::RustcVersion;
71 use rustc_session::{declare_tool_lint, impl_lint_pass};
72 use rustc_span::symbol::{sym, SymbolStr};
73 use rustc_typeck::hir_ty_to_ty;
75 declare_clippy_lint! {
76 /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
78 /// **Why is this bad?** It is better to handle the `None` or `Err` case,
79 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
80 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
81 /// `Allow` by default.
83 /// `result.unwrap()` will let the thread panic on `Err` values.
84 /// Normally, you want to implement more sophisticated error handling,
85 /// and propagate errors upwards with `?` operator.
87 /// Even if you want to panic on errors, not all `Error`s implement good
88 /// messages on display. Therefore, it may be beneficial to look at the places
89 /// where they may get displayed. Activate this lint to do just that.
91 /// **Known problems:** None.
95 /// # let opt = Some(1);
101 /// opt.expect("more helpful message");
107 /// # let res: Result<usize, ()> = Ok(1);
113 /// res.expect("more helpful message");
117 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
120 declare_clippy_lint! {
121 /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
123 /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
124 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
125 /// this lint is `Allow` by default.
127 /// `result.expect()` will let the thread panic on `Err`
128 /// values. Normally, you want to implement more sophisticated error handling,
129 /// and propagate errors upwards with `?` operator.
131 /// **Known problems:** None.
135 /// # let opt = Some(1);
138 /// opt.expect("one");
141 /// let opt = Some(1);
148 /// # let res: Result<usize, ()> = Ok(1);
151 /// res.expect("one");
155 /// # Ok::<(), ()>(())
159 "using `.expect()` on `Result` or `Option`, which might be better handled"
162 declare_clippy_lint! {
163 /// **What it does:** Checks for methods that should live in a trait
164 /// implementation of a `std` trait (see [llogiq's blog
165 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
166 /// information) instead of an inherent implementation.
168 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
169 /// the code, often with very little cost. Also people seeing a `mul(...)`
171 /// may expect `*` to work equally, so you should have good reason to disappoint
174 /// **Known problems:** None.
180 /// fn add(&self, other: &X) -> X {
186 pub SHOULD_IMPLEMENT_TRAIT,
188 "defining a method that should be implementing a std trait"
191 declare_clippy_lint! {
192 /// **What it does:** Checks for methods with certain name prefixes and which
193 /// doesn't match how self is taken. The actual rules are:
195 /// |Prefix |Postfix |`self` taken |
196 /// |-------|------------|----------------------|
197 /// |`as_` | none |`&self` or `&mut self`|
198 /// |`from_`| none | none |
199 /// |`into_`| none |`self` |
200 /// |`is_` | none |`&self` or none |
201 /// |`to_` | `_mut` |`&mut &self` |
202 /// |`to_` | not `_mut` |`&self` |
204 /// **Why is this bad?** Consistency breeds readability. If you follow the
205 /// conventions, your users won't be surprised that they, e.g., need to supply a
206 /// mutable reference to a `as_..` function.
208 /// **Known problems:** None.
214 /// fn as_str(self) -> &'static str {
220 pub WRONG_SELF_CONVENTION,
222 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
225 declare_clippy_lint! {
226 /// **What it does:** This is the same as
227 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
229 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
231 /// **Known problems:** Actually *renaming* the function may break clients if
232 /// the function is part of the public interface. In that case, be mindful of
233 /// the stability guarantees you've given your users.
239 /// pub fn as_str(self) -> &'a str {
244 pub WRONG_PUB_SELF_CONVENTION,
246 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
249 declare_clippy_lint! {
250 /// **What it does:** Checks for usage of `ok().expect(..)`.
252 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
253 /// directly to get a better error message.
255 /// **Known problems:** The error type needs to implement `Debug`
259 /// # let x = Ok::<_, ()>(());
262 /// x.ok().expect("why did I do this again?");
265 /// x.expect("why did I do this again?");
269 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
272 declare_clippy_lint! {
273 /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
274 /// `result.map(_).unwrap_or_else(_)`.
276 /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
277 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
279 /// **Known problems:** The order of the arguments is not in execution order
283 /// # let x = Some(1);
286 /// x.map(|a| a + 1).unwrap_or(0);
289 /// x.map_or(0, |a| a + 1);
295 /// # let x: Result<usize, ()> = Ok(1);
296 /// # fn some_function(foo: ()) -> usize { 1 }
299 /// x.map(|a| a + 1).unwrap_or_else(some_function);
302 /// x.map_or_else(some_function, |a| a + 1);
306 "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)`"
309 declare_clippy_lint! {
310 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
312 /// **Why is this bad?** Readability, this can be written more concisely as
315 /// **Known problems:** The order of the arguments is not in execution order.
319 /// # let opt = Some(1);
322 /// opt.map_or(None, |a| Some(a + 1));
325 /// opt.and_then(|a| Some(a + 1));
327 pub OPTION_MAP_OR_NONE,
329 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
332 declare_clippy_lint! {
333 /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
335 /// **Why is this bad?** Readability, this can be written more concisely as
338 /// **Known problems:** None.
344 /// # let r: Result<u32, &str> = Ok(1);
345 /// assert_eq!(Some(1), r.map_or(None, Some));
350 /// # let r: Result<u32, &str> = Ok(1);
351 /// assert_eq!(Some(1), r.ok());
353 pub RESULT_MAP_OR_INTO_OPTION,
355 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
358 declare_clippy_lint! {
359 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
360 /// `_.or_else(|x| Err(y))`.
362 /// **Why is this bad?** Readability, this can be written more concisely as
363 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
365 /// **Known problems:** None
370 /// # fn opt() -> Option<&'static str> { Some("42") }
371 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
372 /// let _ = opt().and_then(|s| Some(s.len()));
373 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
374 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
377 /// The correct use would be:
380 /// # fn opt() -> Option<&'static str> { Some("42") }
381 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
382 /// let _ = opt().map(|s| s.len());
383 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
384 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
386 pub BIND_INSTEAD_OF_MAP,
388 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
391 declare_clippy_lint! {
392 /// **What it does:** Checks for usage of `_.filter(_).next()`.
394 /// **Why is this bad?** Readability, this can be written more concisely as
397 /// **Known problems:** None.
401 /// # let vec = vec![1];
402 /// vec.iter().filter(|x| **x == 0).next();
404 /// Could be written as
406 /// # let vec = vec![1];
407 /// vec.iter().find(|x| **x == 0);
411 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
414 declare_clippy_lint! {
415 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
417 /// **Why is this bad?** Readability, this can be written more concisely as
418 /// `_.find(!condition)`.
420 /// **Known problems:** None.
424 /// # let vec = vec![1];
425 /// vec.iter().skip_while(|x| **x == 0).next();
427 /// Could be written as
429 /// # let vec = vec![1];
430 /// vec.iter().find(|x| **x != 0);
434 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
437 declare_clippy_lint! {
438 /// **What it does:** Checks for usage of `_.map(_).flatten(_)` on `Iterator` and `Option`
440 /// **Why is this bad?** Readability, this can be written more concisely as
443 /// **Known problems:**
447 /// let vec = vec![vec![1]];
450 /// vec.iter().map(|x| x.iter()).flatten();
453 /// vec.iter().flat_map(|x| x.iter());
457 "using combinations of `flatten` and `map` which can usually be written as a single method call"
460 declare_clippy_lint! {
461 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
462 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
464 /// **Why is this bad?** Readability, this can be written more concisely as
465 /// `_.filter_map(_)`.
467 /// **Known problems:** Often requires a condition + Option/Iterator creation
468 /// inside the closure.
472 /// let vec = vec![1];
475 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
478 /// vec.iter().filter_map(|x| if *x == 0 {
486 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
489 declare_clippy_lint! {
490 /// **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply
491 /// as `filter_map(_)`.
493 /// **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and
496 /// **Known problems:** None.
502 /// .filter(|n| n.checked_add(1).is_some())
503 /// .map(|n| n.checked_add(1).unwrap());
508 /// (0_i32..10).filter_map(|n| n.checked_add(1));
510 pub MANUAL_FILTER_MAP,
512 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
515 declare_clippy_lint! {
516 /// **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply
517 /// as `find_map(_)`.
519 /// **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and
522 /// **Known problems:** None.
528 /// .find(|n| n.checked_add(1).is_some())
529 /// .map(|n| n.checked_add(1).unwrap());
534 /// (0_i32..10).find_map(|n| n.checked_add(1));
538 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
541 declare_clippy_lint! {
542 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
544 /// **Why is this bad?** Readability, this can be written more concisely as
547 /// **Known problems:** None
551 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
553 /// Can be written as
556 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
560 "using combination of `filter_map` and `next` which can usually be written as a single method call"
563 declare_clippy_lint! {
564 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
566 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
568 /// **Known problems:** None
572 /// # let iter = vec![vec![0]].into_iter();
573 /// iter.flat_map(|x| x);
575 /// Can be written as
577 /// # let iter = vec![vec![0]].into_iter();
580 pub FLAT_MAP_IDENTITY,
582 "call to `flat_map` where `flatten` is sufficient"
585 declare_clippy_lint! {
586 /// **What it does:** Checks for an iterator or string search (such as `find()`,
587 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
589 /// **Why is this bad?** Readability, this can be written more concisely as
590 /// `_.any(_)` or `_.contains(_)`.
592 /// **Known problems:** None.
596 /// # let vec = vec![1];
597 /// vec.iter().find(|x| **x == 0).is_some();
599 /// Could be written as
601 /// # let vec = vec![1];
602 /// vec.iter().any(|x| *x == 0);
606 "using an iterator or string search followed by `is_some()`, which is more succinctly expressed as a call to `any()` or `contains()`"
609 declare_clippy_lint! {
610 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
611 /// if it starts with a given char.
613 /// **Why is this bad?** Readability, this can be written more concisely as
614 /// `_.starts_with(_)`.
616 /// **Known problems:** None.
620 /// let name = "foo";
621 /// if name.chars().next() == Some('_') {};
623 /// Could be written as
625 /// let name = "foo";
626 /// if name.starts_with('_') {};
630 "using `.chars().next()` to check if a string starts with a char"
633 declare_clippy_lint! {
634 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
635 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
636 /// `unwrap_or_default` instead.
638 /// **Why is this bad?** The function will always be called and potentially
639 /// allocate an object acting as the default.
641 /// **Known problems:** If the function has side-effects, not calling it will
642 /// change the semantic of the program, but you shouldn't rely on that anyway.
646 /// # let foo = Some(String::new());
647 /// foo.unwrap_or(String::new());
649 /// this can instead be written:
651 /// # let foo = Some(String::new());
652 /// foo.unwrap_or_else(String::new);
656 /// # let foo = Some(String::new());
657 /// foo.unwrap_or_default();
661 "using any `*or` method with a function call, which suggests `*or_else`"
664 declare_clippy_lint! {
665 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
666 /// etc., and suggests to use `unwrap_or_else` instead
668 /// **Why is this bad?** The function will always be called.
670 /// **Known problems:** If the function has side-effects, not calling it will
671 /// change the semantics of the program, but you shouldn't rely on that anyway.
675 /// # let foo = Some(String::new());
676 /// # let err_code = "418";
677 /// # let err_msg = "I'm a teapot";
678 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
682 /// # let foo = Some(String::new());
683 /// # let err_code = "418";
684 /// # let err_msg = "I'm a teapot";
685 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
687 /// this can instead be written:
689 /// # let foo = Some(String::new());
690 /// # let err_code = "418";
691 /// # let err_msg = "I'm a teapot";
692 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
696 "using any `expect` method with a function call"
699 declare_clippy_lint! {
700 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
702 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
703 /// generics, not for using the `clone` method on a concrete type.
705 /// **Known problems:** None.
713 "using `clone` on a `Copy` type"
716 declare_clippy_lint! {
717 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
718 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
719 /// function syntax instead (e.g., `Rc::clone(foo)`).
721 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
722 /// can obscure the fact that only the pointer is being cloned, not the underlying
727 /// # use std::rc::Rc;
728 /// let x = Rc::new(1);
736 pub CLONE_ON_REF_PTR,
738 "using 'clone' on a ref-counted pointer"
741 declare_clippy_lint! {
742 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
744 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
745 /// cloning the underlying `T`.
747 /// **Known problems:** None.
754 /// let z = y.clone();
755 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
758 pub CLONE_DOUBLE_REF,
760 "using `clone` on `&&T`"
763 declare_clippy_lint! {
764 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
765 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
767 /// **Why is this bad?** This bypasses the specialized implementation of
768 /// `ToString` and instead goes through the more expensive string formatting
771 /// **Known problems:** None.
775 /// // Generic implementation for `T: Display` is used (slow)
776 /// ["foo", "bar"].iter().map(|s| s.to_string());
778 /// // OK, the specialized impl is used
779 /// ["foo", "bar"].iter().map(|&s| s.to_string());
781 pub INEFFICIENT_TO_STRING,
783 "using `to_string` on `&&T` where `T: ToString`"
786 declare_clippy_lint! {
787 /// **What it does:** Checks for `new` not returning a type that contains `Self`.
789 /// **Why is this bad?** As a convention, `new` methods are used to make a new
790 /// instance of a type.
792 /// **Known problems:** None.
795 /// In an impl block:
798 /// # struct NotAFoo;
800 /// fn new() -> NotAFoo {
810 /// // Bad. The type name must contain `Self`
811 /// fn new() -> Bar {
819 /// # struct FooError;
821 /// // Good. Return type contains `Self`
822 /// fn new() -> Result<Foo, FooError> {
828 /// Or in a trait definition:
830 /// pub trait Trait {
831 /// // Bad. The type name must contain `Self`
837 /// pub trait Trait {
838 /// // Good. Return type contains `Self`
839 /// fn new() -> Self;
844 "not returning type containing `Self` in a `new` method"
847 declare_clippy_lint! {
848 /// **What it does:** Checks for string methods that receive a single-character
849 /// `str` as an argument, e.g., `_.split("x")`.
851 /// **Why is this bad?** Performing these methods using a `char` is faster than
854 /// **Known problems:** Does not catch multi-byte unicode characters.
863 pub SINGLE_CHAR_PATTERN,
865 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
868 declare_clippy_lint! {
869 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
871 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
872 /// actually intend to panic.
874 /// **Known problems:** None.
877 /// ```rust,should_panic
878 /// for x in (0..100).step_by(0) {
882 pub ITERATOR_STEP_BY_ZERO,
884 "using `Iterator::step_by(0)`, which will panic at runtime"
887 declare_clippy_lint! {
888 /// **What it does:** Checks for the use of `iter.nth(0)`.
890 /// **Why is this bad?** `iter.next()` is equivalent to
891 /// `iter.nth(0)`, as they both consume the next element,
892 /// but is more readable.
894 /// **Known problems:** None.
899 /// # use std::collections::HashSet;
901 /// # let mut s = HashSet::new();
903 /// let x = s.iter().nth(0);
906 /// # let mut s = HashSet::new();
908 /// let x = s.iter().next();
912 "replace `iter.nth(0)` with `iter.next()`"
915 declare_clippy_lint! {
916 /// **What it does:** Checks for use of `.iter().nth()` (and the related
917 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
919 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
922 /// **Known problems:** None.
926 /// let some_vec = vec![0, 1, 2, 3];
927 /// let bad_vec = some_vec.iter().nth(3);
928 /// let bad_slice = &some_vec[..].iter().nth(3);
930 /// The correct use would be:
932 /// let some_vec = vec![0, 1, 2, 3];
933 /// let bad_vec = some_vec.get(3);
934 /// let bad_slice = &some_vec[..].get(3);
938 "using `.iter().nth()` on a standard library type with O(1) element access"
941 declare_clippy_lint! {
942 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
944 /// **Why is this bad?** `.nth(x)` is cleaner
946 /// **Known problems:** None.
950 /// let some_vec = vec![0, 1, 2, 3];
951 /// let bad_vec = some_vec.iter().skip(3).next();
952 /// let bad_slice = &some_vec[..].iter().skip(3).next();
954 /// The correct use would be:
956 /// let some_vec = vec![0, 1, 2, 3];
957 /// let bad_vec = some_vec.iter().nth(3);
958 /// let bad_slice = &some_vec[..].iter().nth(3);
962 "using `.skip(x).next()` on an iterator"
965 declare_clippy_lint! {
966 /// **What it does:** Checks for use of `.get().unwrap()` (or
967 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
969 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
972 /// **Known problems:** Not a replacement for error handling: Using either
973 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
974 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
975 /// temporary placeholder for dealing with the `Option` type, then this does
976 /// not mitigate the need for error handling. If there is a chance that `.get()`
977 /// will be `None` in your program, then it is advisable that the `None` case
978 /// is handled in a future refactor instead of using `.unwrap()` or the Index
983 /// let mut some_vec = vec![0, 1, 2, 3];
984 /// let last = some_vec.get(3).unwrap();
985 /// *some_vec.get_mut(0).unwrap() = 1;
987 /// The correct use would be:
989 /// let mut some_vec = vec![0, 1, 2, 3];
990 /// let last = some_vec[3];
995 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
998 declare_clippy_lint! {
999 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
1000 /// `&str` or `String`.
1002 /// **Why is this bad?** `.push_str(s)` is clearer
1004 /// **Known problems:** None.
1008 /// let abc = "abc";
1009 /// let def = String::from("def");
1010 /// let mut s = String::new();
1011 /// s.extend(abc.chars());
1012 /// s.extend(def.chars());
1014 /// The correct use would be:
1016 /// let abc = "abc";
1017 /// let def = String::from("def");
1018 /// let mut s = String::new();
1019 /// s.push_str(abc);
1020 /// s.push_str(&def);
1022 pub STRING_EXTEND_CHARS,
1024 "using `x.extend(s.chars())` where s is a `&str` or `String`"
1027 declare_clippy_lint! {
1028 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
1031 /// **Why is this bad?** `.to_vec()` is clearer
1033 /// **Known problems:** None.
1037 /// let s = [1, 2, 3, 4, 5];
1038 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1040 /// The better use would be:
1042 /// let s = [1, 2, 3, 4, 5];
1043 /// let s2: Vec<isize> = s.to_vec();
1045 pub ITER_CLONED_COLLECT,
1047 "using `.cloned().collect()` on slice to create a `Vec`"
1050 declare_clippy_lint! {
1051 /// **What it does:** Checks for usage of `_.chars().last()` or
1052 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1054 /// **Why is this bad?** Readability, this can be written more concisely as
1055 /// `_.ends_with(_)`.
1057 /// **Known problems:** None.
1061 /// # let name = "_";
1064 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1067 /// name.ends_with('_') || name.ends_with('-');
1071 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1074 declare_clippy_lint! {
1075 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
1076 /// types before and after the call are the same.
1078 /// **Why is this bad?** The call is unnecessary.
1080 /// **Known problems:** None.
1084 /// # fn do_stuff(x: &[i32]) {}
1085 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1086 /// do_stuff(x.as_ref());
1088 /// The correct use would be:
1090 /// # fn do_stuff(x: &[i32]) {}
1091 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1096 "using `as_ref` where the types before and after the call are the same"
1099 declare_clippy_lint! {
1100 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1101 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1102 /// `sum` or `product`.
1104 /// **Why is this bad?** Readability.
1106 /// **Known problems:** None.
1110 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1112 /// This could be written as:
1114 /// let _ = (0..3).any(|x| x > 2);
1116 pub UNNECESSARY_FOLD,
1118 "using `fold` when a more succinct alternative exists"
1121 declare_clippy_lint! {
1122 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1123 /// More specifically it checks if the closure provided is only performing one of the
1124 /// filter or map operations and suggests the appropriate option.
1126 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1127 /// operation is being performed.
1129 /// **Known problems:** None
1133 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1135 /// // As there is no transformation of the argument this could be written as:
1136 /// let _ = (0..3).filter(|&x| x > 2);
1140 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1142 /// // As there is no conditional check on the argument this could be written as:
1143 /// let _ = (0..4).map(|x| x + 1);
1145 pub UNNECESSARY_FILTER_MAP,
1147 "using `filter_map` when a more succinct alternative exists"
1150 declare_clippy_lint! {
1151 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1154 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1155 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1156 /// `iter_mut` directly.
1158 /// **Known problems:** None
1164 /// let _ = (&vec![3, 4, 5]).into_iter();
1167 /// let _ = (&vec![3, 4, 5]).iter();
1169 pub INTO_ITER_ON_REF,
1171 "using `.into_iter()` on a reference"
1174 declare_clippy_lint! {
1175 /// **What it does:** Checks for calls to `map` followed by a `count`.
1177 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1178 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1179 /// drive the iterator to completion, you can just use `for_each` instead.
1181 /// **Known problems:** None
1186 /// let _ = (0..3).map(|x| x + 2).count();
1190 "suspicious usage of map"
1193 declare_clippy_lint! {
1194 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1196 /// **Why is this bad?** For most types, this is undefined behavior.
1198 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1199 /// of `MaybeUninit`. There may be other types that allow uninitialized
1200 /// data, but those are not yet rigorously defined.
1205 /// // Beware the UB
1206 /// use std::mem::MaybeUninit;
1208 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1211 /// Note that the following is OK:
1214 /// use std::mem::MaybeUninit;
1216 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1217 /// MaybeUninit::uninit().assume_init()
1220 pub UNINIT_ASSUMED_INIT,
1222 "`MaybeUninit::uninit().assume_init()`"
1225 declare_clippy_lint! {
1226 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1228 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1233 /// # let y: u32 = 0;
1234 /// # let x: u32 = 100;
1235 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1236 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1239 /// can be written using dedicated methods for saturating addition/subtraction as:
1242 /// # let y: u32 = 0;
1243 /// # let x: u32 = 100;
1244 /// let add = x.saturating_add(y);
1245 /// let sub = x.saturating_sub(y);
1247 pub MANUAL_SATURATING_ARITHMETIC,
1249 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1252 declare_clippy_lint! {
1253 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1254 /// zero-sized types
1256 /// **Why is this bad?** This is a no-op, and likely unintended
1258 /// **Known problems:** None
1262 /// unsafe { (&() as *const ()).offset(1) };
1266 "Check for offset calculations on raw pointers to zero-sized types"
1269 declare_clippy_lint! {
1270 /// **What it does:** Checks for `FileType::is_file()`.
1272 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1273 /// they are testing whether a path is something they can get bytes from. But
1274 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1275 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1281 /// let metadata = std::fs::metadata("foo.txt")?;
1282 /// let filetype = metadata.file_type();
1284 /// if filetype.is_file() {
1287 /// # Ok::<_, std::io::Error>(())
1291 /// should be written as:
1295 /// let metadata = std::fs::metadata("foo.txt")?;
1296 /// let filetype = metadata.file_type();
1298 /// if !filetype.is_dir() {
1301 /// # Ok::<_, std::io::Error>(())
1304 pub FILETYPE_IS_FILE,
1306 "`FileType::is_file` is not recommended to test for readable file type"
1309 declare_clippy_lint! {
1310 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1312 /// **Why is this bad?** Readability, this can be written more concisely as
1315 /// **Known problems:** None.
1319 /// # let opt = Some("".to_string());
1320 /// opt.as_ref().map(String::as_str)
1323 /// Can be written as
1325 /// # let opt = Some("".to_string());
1329 pub OPTION_AS_REF_DEREF,
1331 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1334 declare_clippy_lint! {
1335 /// **What it does:** Checks for usage of `iter().next()` on a Slice or an Array
1337 /// **Why is this bad?** These can be shortened into `.get()`
1339 /// **Known problems:** None.
1343 /// # let a = [1, 2, 3];
1344 /// # let b = vec![1, 2, 3];
1345 /// a[2..].iter().next();
1346 /// b.iter().next();
1348 /// should be written as:
1350 /// # let a = [1, 2, 3];
1351 /// # let b = vec![1, 2, 3];
1355 pub ITER_NEXT_SLICE,
1357 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1360 declare_clippy_lint! {
1361 /// **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal
1362 /// where `push`/`insert` with a `char` would work fine.
1364 /// **Why is this bad?** It's less clear that we are pushing a single character.
1366 /// **Known problems:** None
1370 /// let mut string = String::new();
1371 /// string.insert_str(0, "R");
1372 /// string.push_str("R");
1374 /// Could be written as
1376 /// let mut string = String::new();
1377 /// string.insert(0, 'R');
1378 /// string.push('R');
1380 pub SINGLE_CHAR_ADD_STR,
1382 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1385 declare_clippy_lint! {
1386 /// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1387 /// lazily evaluated closures on `Option` and `Result`.
1389 /// This lint suggests changing the following functions, when eager evaluation results in
1391 /// - `unwrap_or_else` to `unwrap_or`
1392 /// - `and_then` to `and`
1393 /// - `or_else` to `or`
1394 /// - `get_or_insert_with` to `get_or_insert`
1395 /// - `ok_or_else` to `ok_or`
1397 /// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1399 /// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1400 /// side effects. Eagerly evaluating them can change the semantics of the program.
1405 /// // example code where clippy issues a warning
1406 /// let opt: Option<u32> = None;
1408 /// opt.unwrap_or_else(|| 42);
1412 /// let opt: Option<u32> = None;
1414 /// opt.unwrap_or(42);
1416 pub UNNECESSARY_LAZY_EVALUATIONS,
1418 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1421 declare_clippy_lint! {
1422 /// **What it does:** Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1424 /// **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.
1426 /// **Known problems:** None
1431 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1435 /// (0..3).try_for_each(|t| Err(t));
1437 pub MAP_COLLECT_RESULT_UNIT,
1439 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1442 declare_clippy_lint! {
1443 /// **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator`
1446 /// **Why is this bad?** It is recommended style to use collect. See
1447 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1449 /// **Known problems:** None.
1454 /// use std::iter::FromIterator;
1456 /// let five_fives = std::iter::repeat(5).take(5);
1458 /// let v = Vec::from_iter(five_fives);
1460 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1464 /// let five_fives = std::iter::repeat(5).take(5);
1466 /// let v: Vec<i32> = five_fives.collect();
1468 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1470 pub FROM_ITER_INSTEAD_OF_COLLECT,
1472 "use `.collect()` instead of `::from_iter()`"
1475 declare_clippy_lint! {
1476 /// **What it does:** Checks for usage of `inspect().for_each()`.
1478 /// **Why is this bad?** It is the same as performing the computation
1479 /// inside `inspect` at the beginning of the closure in `for_each`.
1481 /// **Known problems:** None.
1486 /// [1,2,3,4,5].iter()
1487 /// .inspect(|&x| println!("inspect the number: {}", x))
1488 /// .for_each(|&x| {
1489 /// assert!(x >= 0);
1492 /// Can be written as
1494 /// [1,2,3,4,5].iter()
1495 /// .for_each(|&x| {
1496 /// println!("inspect the number: {}", x);
1497 /// assert!(x >= 0);
1500 pub INSPECT_FOR_EACH,
1502 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1505 declare_clippy_lint! {
1506 /// **What it does:** Checks for usage of `filter_map(|x| x)`.
1508 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
1510 /// **Known problems:** None.
1515 /// # let iter = vec![Some(1)].into_iter();
1516 /// iter.filter_map(|x| x);
1520 /// # let iter = vec![Some(1)].into_iter();
1523 pub FILTER_MAP_IDENTITY,
1525 "call to `filter_map` where `flatten` is sufficient"
1528 declare_clippy_lint! {
1529 /// **What it does:** Checks for the use of `.bytes().nth()`.
1531 /// **Why is this bad?** `.as_bytes().get()` is more efficient and more
1534 /// **Known problems:** None.
1540 /// let _ = "Hello".bytes().nth(3);
1543 /// let _ = "Hello".as_bytes().get(3);
1547 "replace `.bytes().nth()` with `.as_bytes().get()`"
1550 declare_clippy_lint! {
1551 /// **What it does:** Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1553 /// **Why is this bad?** These methods do the same thing as `_.clone()` but may be confusing as
1554 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1556 /// **Known problems:** None.
1561 /// let a = vec![1, 2, 3];
1562 /// let b = a.to_vec();
1563 /// let c = a.to_owned();
1567 /// let a = vec![1, 2, 3];
1568 /// let b = a.clone();
1569 /// let c = a.clone();
1573 "implicitly cloning a value by invoking a function on its dereferenced type"
1576 declare_clippy_lint! {
1577 /// **What it does:** Checks for the use of `.iter().count()`.
1579 /// **Why is this bad?** `.len()` is more efficient and more
1582 /// **Known problems:** None.
1588 /// let some_vec = vec![0, 1, 2, 3];
1589 /// let _ = some_vec.iter().count();
1590 /// let _ = &some_vec[..].iter().count();
1593 /// let some_vec = vec![0, 1, 2, 3];
1594 /// let _ = some_vec.len();
1595 /// let _ = &some_vec[..].len();
1599 "replace `.iter().count()` with `.len()`"
1602 pub struct Methods {
1603 msrv: Option<RustcVersion>,
1608 pub fn new(msrv: Option<RustcVersion>) -> Self {
1613 impl_lint_pass!(Methods => [
1616 SHOULD_IMPLEMENT_TRAIT,
1617 WRONG_SELF_CONVENTION,
1618 WRONG_PUB_SELF_CONVENTION,
1621 RESULT_MAP_OR_INTO_OPTION,
1623 BIND_INSTEAD_OF_MAP,
1631 INEFFICIENT_TO_STRING,
1633 SINGLE_CHAR_PATTERN,
1634 SINGLE_CHAR_ADD_STR,
1639 FILTER_MAP_IDENTITY,
1645 ITERATOR_STEP_BY_ZERO,
1653 STRING_EXTEND_CHARS,
1654 ITER_CLONED_COLLECT,
1657 UNNECESSARY_FILTER_MAP,
1660 UNINIT_ASSUMED_INIT,
1661 MANUAL_SATURATING_ARITHMETIC,
1664 OPTION_AS_REF_DEREF,
1665 UNNECESSARY_LAZY_EVALUATIONS,
1666 MAP_COLLECT_RESULT_UNIT,
1667 FROM_ITER_INSTEAD_OF_COLLECT,
1672 impl<'tcx> LateLintPass<'tcx> for Methods {
1673 #[allow(clippy::too_many_lines)]
1674 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1675 if in_macro(expr.span) {
1679 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1680 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1681 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1683 match method_names.as_slice() {
1684 ["unwrap", "get"] => get_unwrap::check(cx, expr, arg_lists[1], false),
1685 ["unwrap", "get_mut"] => get_unwrap::check(cx, expr, arg_lists[1], true),
1686 ["unwrap", ..] => unwrap_used::check(cx, expr, arg_lists[0]),
1687 ["expect", "ok"] => ok_expect::check(cx, expr, arg_lists[1]),
1688 ["expect", ..] => expect_used::check(cx, expr, arg_lists[0]),
1689 ["unwrap_or", "map"] => option_map_unwrap_or::check(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1690 ["unwrap_or_else", "map"] => {
1691 if !map_unwrap_or::check(cx, expr, arg_lists[1], arg_lists[0], self.msrv.as_ref()) {
1692 unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "unwrap_or");
1695 ["map_or", ..] => option_map_or_none::check(cx, expr, arg_lists[0]),
1696 ["and_then", ..] => {
1697 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::check(cx, expr, arg_lists[0]);
1698 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::check(cx, expr, arg_lists[0]);
1699 if !biom_option_linted && !biom_result_linted {
1700 unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "and");
1703 ["or_else", ..] => {
1704 if !bind_instead_of_map::ResultOrElseErrInfo::check(cx, expr, arg_lists[0]) {
1705 unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "or");
1708 ["next", "filter"] => filter_next::check(cx, expr, arg_lists[1]),
1709 ["next", "skip_while"] => skip_while_next::check(cx, expr, arg_lists[1]),
1710 ["next", "iter"] => iter_next_slice::check(cx, expr, arg_lists[1]),
1711 ["map", "filter"] => filter_map::check(cx, expr, false),
1712 ["map", "filter_map"] => filter_map_map::check(cx, expr, arg_lists[1], arg_lists[0]),
1713 ["next", "filter_map"] => filter_map_next::check(cx, expr, arg_lists[1], self.msrv.as_ref()),
1714 ["map", "find"] => filter_map::check(cx, expr, true),
1715 ["flat_map", "filter"] => filter_flat_map::check(cx, expr, arg_lists[1], arg_lists[0]),
1716 ["flat_map", "filter_map"] => filter_map_flat_map::check(cx, expr, arg_lists[1], arg_lists[0]),
1717 ["flat_map", ..] => flat_map_identity::check(cx, expr, arg_lists[0], method_spans[0]),
1718 ["flatten", "map"] => map_flatten::check(cx, expr, arg_lists[1]),
1719 ["is_some", "find"] => search_is_some::check(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1720 ["is_some", "position"] => {
1721 search_is_some::check(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1723 ["is_some", "rposition"] => {
1724 search_is_some::check(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1726 ["extend", ..] => string_extend_chars::check(cx, expr, arg_lists[0]),
1727 ["count", "into_iter"] => iter_count::check(cx, expr, &arg_lists[1], "into_iter"),
1728 ["count", "iter"] => iter_count::check(cx, expr, &arg_lists[1], "iter"),
1729 ["count", "iter_mut"] => iter_count::check(cx, expr, &arg_lists[1], "iter_mut"),
1730 ["nth", "iter"] => iter_nth::check(cx, expr, &arg_lists, false),
1731 ["nth", "iter_mut"] => iter_nth::check(cx, expr, &arg_lists, true),
1732 ["nth", "bytes"] => bytes_nth::check(cx, expr, &arg_lists[1]),
1733 ["nth", ..] => iter_nth_zero::check(cx, expr, arg_lists[0]),
1734 ["step_by", ..] => iterator_step_by_zero::check(cx, expr, arg_lists[0]),
1735 ["next", "skip"] => iter_skip_next::check(cx, expr, arg_lists[1]),
1736 ["collect", "cloned"] => iter_cloned_collect::check(cx, expr, arg_lists[1]),
1737 ["as_ref"] => useless_asref::check(cx, expr, "as_ref", arg_lists[0]),
1738 ["as_mut"] => useless_asref::check(cx, expr, "as_mut", arg_lists[0]),
1739 ["fold", ..] => unnecessary_fold::check(cx, expr, arg_lists[0], method_spans[0]),
1740 ["filter_map", ..] => {
1741 unnecessary_filter_map::check(cx, expr, arg_lists[0]);
1742 filter_map_identity::check(cx, expr, arg_lists[0], method_spans[0]);
1744 ["count", "map"] => suspicious_map::check(cx, expr, arg_lists[1], arg_lists[0]),
1745 ["assume_init"] => uninit_assumed_init::check(cx, &arg_lists[0][0], expr),
1746 ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
1747 manual_saturating_arithmetic::check(cx, expr, &arg_lists, &arith["checked_".len()..])
1749 ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
1750 zst_offset::check(cx, expr, arg_lists[0])
1752 ["is_file", ..] => filetype_is_file::check(cx, expr, arg_lists[0]),
1753 ["map", "as_ref"] => {
1754 option_as_ref_deref::check(cx, expr, arg_lists[1], arg_lists[0], false, self.msrv.as_ref())
1756 ["map", "as_mut"] => {
1757 option_as_ref_deref::check(cx, expr, arg_lists[1], arg_lists[0], true, self.msrv.as_ref())
1759 ["unwrap_or_else", ..] => unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "unwrap_or"),
1760 ["get_or_insert_with", ..] => unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "get_or_insert"),
1761 ["ok_or_else", ..] => unnecessary_lazy_eval::check(cx, expr, arg_lists[0], "ok_or"),
1762 ["collect", "map"] => map_collect_result_unit::check(cx, expr, arg_lists[1], arg_lists[0]),
1763 ["for_each", "inspect"] => inspect_for_each::check(cx, expr, method_spans[1]),
1764 ["to_owned", ..] => implicit_clone::check(cx, expr, sym::ToOwned),
1765 ["to_os_string", ..] => implicit_clone::check(cx, expr, sym::OsStr),
1766 ["to_path_buf", ..] => implicit_clone::check(cx, expr, sym::Path),
1767 ["to_vec", ..] => implicit_clone::check(cx, expr, sym::slice),
1772 hir::ExprKind::Call(ref func, ref args) => {
1773 if let hir::ExprKind::Path(path) = &func.kind {
1774 if match_qpath(path, &["from_iter"]) {
1775 from_iter_instead_of_collect::check(cx, expr, args);
1779 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
1780 or_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1781 expect_fun_call::check(cx, expr, *method_span, &method_call.ident.as_str(), args);
1783 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
1784 if args.len() == 1 && method_call.ident.name == sym::clone {
1785 clone_on_copy::check(cx, expr, &args[0], self_ty);
1786 clone_on_ref_ptr::check(cx, expr, &args[0]);
1788 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1789 inefficient_to_string::check(cx, expr, &args[0], self_ty);
1792 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
1793 if match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
1794 single_char_push_string::check(cx, expr, args);
1795 } else if match_def_path(cx, fn_def_id, &paths::INSERT_STR) {
1796 single_char_insert_string::check(cx, expr, args);
1800 match self_ty.kind() {
1801 ty::Ref(_, ty, _) if *ty.kind() == ty::Str => {
1802 for &(method, pos) in &PATTERN_METHODS {
1803 if method_call.ident.name.as_str() == method && args.len() > pos {
1804 single_char_pattern::check(cx, expr, &args[pos]);
1808 ty::Ref(..) if method_call.ident.name == sym::into_iter => {
1809 into_iter_on_ref::check(cx, expr, self_ty, *method_span);
1814 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1815 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1817 let mut info = BinaryExprInfo {
1821 eq: op.node == hir::BinOpKind::Eq,
1823 lint_binary_expr_with_method_call(cx, &mut info);
1829 #[allow(clippy::too_many_lines)]
1830 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1831 if in_external_macro(cx.sess(), impl_item.span) {
1834 let name = impl_item.ident.name.as_str();
1835 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
1836 let item = cx.tcx.hir().expect_item(parent);
1837 let self_ty = cx.tcx.type_of(item.def_id);
1839 // if this impl block implements a trait, lint in trait definition instead
1840 if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
1845 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1846 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1848 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
1849 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1851 let first_arg_ty = &method_sig.inputs().iter().next();
1853 // check conventions w.r.t. conversion method names and predicates
1854 if let Some(first_arg_ty) = first_arg_ty;
1857 if cx.access_levels.is_exported(impl_item.hir_id()) {
1858 // check missing trait implementations
1859 for method_config in &TRAIT_METHODS {
1860 if name == method_config.method_name &&
1861 sig.decl.inputs.len() == method_config.param_count &&
1862 method_config.output_type.matches(cx, &sig.decl.output) &&
1863 method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1864 fn_header_equals(method_config.fn_header, sig.header) &&
1865 method_config.lifetime_param_cond(&impl_item)
1869 SHOULD_IMPLEMENT_TRAIT,
1872 "method `{}` can be confused for the standard trait method `{}::{}`",
1873 method_config.method_name,
1874 method_config.trait_name,
1875 method_config.method_name
1879 "consider implementing the trait `{}` or choosing a less ambiguous method name",
1880 method_config.trait_name
1887 wrong_self_convention::check(
1890 item.vis.node.is_pub(),
1898 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1899 let ret_ty = return_ty(cx, impl_item.hir_id());
1901 // walk the return type and check for Self (this does not check associated types)
1902 if contains_ty(ret_ty, self_ty) {
1906 // if return type is impl trait, check the associated types
1907 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
1908 // one of the associated types must be Self
1909 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
1910 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1911 // walk the associated type and check for Self
1912 if contains_ty(projection_predicate.ty, self_ty) {
1919 if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1924 "methods called `new` usually return `Self`",
1930 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1931 if in_external_macro(cx.tcx.sess, item.span) {
1936 if let TraitItemKind::Fn(ref sig, _) = item.kind;
1937 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
1938 let first_arg_span = first_arg_ty.span;
1939 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
1940 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1943 wrong_self_convention::check(
1945 &item.ident.name.as_str(),
1955 if item.ident.name == sym::new;
1956 if let TraitItemKind::Fn(_, _) = item.kind;
1957 let ret_ty = return_ty(cx, item.hir_id());
1958 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1959 if !contains_ty(ret_ty, self_ty);
1966 "methods called `new` usually return `Self`",
1972 extract_msrv_attr!(LateContext);
1975 fn derefs_to_slice<'tcx>(
1976 cx: &LateContext<'tcx>,
1977 expr: &'tcx hir::Expr<'tcx>,
1979 ) -> Option<&'tcx hir::Expr<'tcx>> {
1980 fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
1982 ty::Slice(_) => true,
1983 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1984 ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type),
1985 ty::Array(_, size) => size
1986 .try_eval_usize(cx.tcx, cx.param_env)
1987 .map_or(false, |size| size < 32),
1988 ty::Ref(_, inner, _) => may_slice(cx, inner),
1993 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
1994 if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
2001 ty::Slice(_) => Some(expr),
2002 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2003 ty::Ref(_, inner, _) => {
2004 if may_slice(cx, inner) {
2015 /// Used for `lint_binary_expr_with_method_call`.
2016 #[derive(Copy, Clone)]
2017 struct BinaryExprInfo<'a> {
2018 expr: &'a hir::Expr<'a>,
2019 chain: &'a hir::Expr<'a>,
2020 other: &'a hir::Expr<'a>,
2024 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2025 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
2026 macro_rules! lint_with_both_lhs_and_rhs {
2027 ($func:ident, $cx:expr, $info:ident) => {
2028 if !$func($cx, $info) {
2029 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2030 if $func($cx, $info) {
2037 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2038 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2039 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2040 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2043 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2045 cx: &LateContext<'_>,
2046 info: &BinaryExprInfo<'_>,
2047 chain_methods: &[&str],
2048 lint: &'static Lint,
2052 if let Some(args) = method_chain_args(info.chain, chain_methods);
2053 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2054 if arg_char.len() == 1;
2055 if let hir::ExprKind::Path(ref qpath) = fun.kind;
2056 if let Some(segment) = single_segment_path(qpath);
2057 if segment.ident.name == sym::Some;
2059 let mut applicability = Applicability::MachineApplicable;
2060 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
2062 if *self_ty.kind() != ty::Str {
2070 &format!("you should use the `{}` method", suggest),
2072 format!("{}{}.{}({})",
2073 if info.eq { "" } else { "!" },
2074 snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
2076 snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
2087 /// Checks for the `CHARS_NEXT_CMP` lint.
2088 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2089 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2092 /// Checks for the `CHARS_LAST_CMP` lint.
2093 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2094 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2097 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2101 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2102 fn lint_chars_cmp_with_unwrap<'tcx>(
2103 cx: &LateContext<'tcx>,
2104 info: &BinaryExprInfo<'_>,
2105 chain_methods: &[&str],
2106 lint: &'static Lint,
2110 if let Some(args) = method_chain_args(info.chain, chain_methods);
2111 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2112 if let ast::LitKind::Char(c) = lit.node;
2114 let mut applicability = Applicability::MachineApplicable;
2119 &format!("you should use the `{}` method", suggest),
2121 format!("{}{}.{}('{}')",
2122 if info.eq { "" } else { "!" },
2123 snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
2136 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2137 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2138 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2141 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2142 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2143 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
2146 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
2150 fn get_hint_if_single_char_arg(
2151 cx: &LateContext<'_>,
2152 arg: &hir::Expr<'_>,
2153 applicability: &mut Applicability,
2154 ) -> Option<String> {
2156 if let hir::ExprKind::Lit(lit) = &arg.kind;
2157 if let ast::LitKind::Str(r, style) = lit.node;
2158 let string = r.as_str();
2159 if string.chars().count() == 1;
2161 let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
2162 let ch = if let ast::StrStyle::Raw(nhash) = style {
2163 let nhash = nhash as usize;
2164 // for raw string: r##"a"##
2165 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
2167 // for regular string: "a"
2168 &snip[1..(snip.len() - 1)]
2170 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
2178 const FN_HEADER: hir::FnHeader = hir::FnHeader {
2179 unsafety: hir::Unsafety::Normal,
2180 constness: hir::Constness::NotConst,
2181 asyncness: hir::IsAsync::NotAsync,
2182 abi: rustc_target::spec::abi::Abi::Rust,
2185 struct ShouldImplTraitCase {
2186 trait_name: &'static str,
2187 method_name: &'static str,
2189 fn_header: hir::FnHeader,
2190 // implicit self kind expected (none, self, &self, ...)
2191 self_kind: SelfKind,
2192 // checks against the output type
2193 output_type: OutType,
2194 // certain methods with explicit lifetimes can't implement the equivalent trait method
2195 lint_explicit_lifetime: bool,
2197 impl ShouldImplTraitCase {
2199 trait_name: &'static str,
2200 method_name: &'static str,
2202 fn_header: hir::FnHeader,
2203 self_kind: SelfKind,
2204 output_type: OutType,
2205 lint_explicit_lifetime: bool,
2206 ) -> ShouldImplTraitCase {
2207 ShouldImplTraitCase {
2214 lint_explicit_lifetime,
2218 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
2219 self.lint_explicit_lifetime
2220 || !impl_item.generics.params.iter().any(|p| {
2223 hir::GenericParamKind::Lifetime {
2224 kind: hir::LifetimeParamKind::Explicit
2232 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
2233 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2234 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2235 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2236 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2237 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2238 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2239 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2240 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2241 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2242 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
2243 // FIXME: default doesn't work
2244 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
2245 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2246 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2247 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2248 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
2249 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
2250 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2251 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
2252 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
2253 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
2254 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
2255 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2256 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2257 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2258 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
2259 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
2260 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2261 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2262 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2263 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
2267 const PATTERN_METHODS: [(&str, usize); 17] = [
2275 ("split_terminator", 1),
2276 ("rsplit_terminator", 1),
2281 ("match_indices", 1),
2282 ("rmatch_indices", 1),
2283 ("trim_start_matches", 1),
2284 ("trim_end_matches", 1),
2287 #[derive(Clone, Copy, PartialEq, Debug)]
2296 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2297 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
2298 if ty == parent_ty {
2300 } else if ty.is_box() {
2301 ty.boxed_ty() == parent_ty
2302 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
2303 if let ty::Adt(_, substs) = ty.kind() {
2304 substs.types().next().map_or(false, |t| t == parent_ty)
2313 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
2314 if let ty::Ref(_, t, m) = *ty.kind() {
2315 return m == mutability && t == parent_ty;
2318 let trait_path = match mutability {
2319 hir::Mutability::Not => &paths::ASREF_TRAIT,
2320 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
2323 let trait_def_id = match get_trait_def_id(cx, trait_path) {
2325 None => return false,
2327 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
2331 Self::Value => matches_value(cx, parent_ty, ty),
2332 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
2333 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
2334 Self::No => ty != parent_ty,
2339 fn description(self) -> &'static str {
2341 Self::Value => "self by value",
2342 Self::Ref => "self by reference",
2343 Self::RefMut => "self by mutable reference",
2344 Self::No => "no self",
2349 #[derive(Clone, Copy)]
2358 fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
2359 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
2361 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
2362 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
2363 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
2364 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
2365 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
2371 fn is_bool(ty: &hir::Ty<'_>) -> bool {
2372 if let hir::TyKind::Path(ref p) = ty.kind {
2373 match_qpath(p, &["bool"])
2379 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
2380 expected.constness == actual.constness
2381 && expected.unsafety == actual.unsafety
2382 && expected.asyncness == actual.asyncness