1 mod bind_instead_of_map;
3 mod filter_map_identity;
4 mod inefficient_to_string;
6 mod manual_saturating_arithmetic;
7 mod option_map_unwrap_or;
8 mod unnecessary_filter_map;
9 mod unnecessary_lazy_eval;
15 use bind_instead_of_map::BindInsteadOfMap;
16 use if_chain::if_chain;
18 use rustc_errors::Applicability;
20 use rustc_hir::{Expr, ExprKind, PatKind, TraitItem, TraitItemKind, UnOp};
21 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
22 use rustc_middle::lint::in_external_macro;
23 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
24 use rustc_semver::RustcVersion;
25 use rustc_session::{declare_tool_lint, impl_lint_pass};
26 use rustc_span::source_map::Span;
27 use rustc_span::symbol::{sym, SymbolStr};
28 use rustc_typeck::hir_ty_to_ty;
30 use crate::consts::{constant, Constant};
31 use crate::utils::eager_or_lazy::is_lazyness_candidate;
32 use crate::utils::usage::mutated_variables;
34 contains_return, contains_ty, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
35 in_macro, is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment, match_def_path,
36 match_qpath, match_trait_method, match_type, meets_msrv, method_calls, method_chain_args, path_to_local_id, paths,
37 remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite,
38 span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, strip_pat_refs, sugg, walk_ptrs_ty_depth,
42 declare_clippy_lint! {
43 /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
45 /// **Why is this bad?** It is better to handle the `None` or `Err` case,
46 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
47 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
48 /// `Allow` by default.
50 /// `result.unwrap()` will let the thread panic on `Err` values.
51 /// Normally, you want to implement more sophisticated error handling,
52 /// and propagate errors upwards with `?` operator.
54 /// Even if you want to panic on errors, not all `Error`s implement good
55 /// messages on display. Therefore, it may be beneficial to look at the places
56 /// where they may get displayed. Activate this lint to do just that.
58 /// **Known problems:** None.
62 /// # let opt = Some(1);
68 /// opt.expect("more helpful message");
74 /// # let res: Result<usize, ()> = Ok(1);
80 /// res.expect("more helpful message");
84 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
87 declare_clippy_lint! {
88 /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
90 /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
91 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
92 /// this lint is `Allow` by default.
94 /// `result.expect()` will let the thread panic on `Err`
95 /// values. Normally, you want to implement more sophisticated error handling,
96 /// and propagate errors upwards with `?` operator.
98 /// **Known problems:** None.
102 /// # let opt = Some(1);
105 /// opt.expect("one");
108 /// let opt = Some(1);
115 /// # let res: Result<usize, ()> = Ok(1);
118 /// res.expect("one");
122 /// # Ok::<(), ()>(())
126 "using `.expect()` on `Result` or `Option`, which might be better handled"
129 declare_clippy_lint! {
130 /// **What it does:** Checks for methods that should live in a trait
131 /// implementation of a `std` trait (see [llogiq's blog
132 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
133 /// information) instead of an inherent implementation.
135 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
136 /// the code, often with very little cost. Also people seeing a `mul(...)`
138 /// may expect `*` to work equally, so you should have good reason to disappoint
141 /// **Known problems:** None.
147 /// fn add(&self, other: &X) -> X {
153 pub SHOULD_IMPLEMENT_TRAIT,
155 "defining a method that should be implementing a std trait"
158 declare_clippy_lint! {
159 /// **What it does:** Checks for methods with certain name prefixes and which
160 /// doesn't match how self is taken. The actual rules are:
162 /// |Prefix |`self` taken |
163 /// |-------|----------------------|
164 /// |`as_` |`&self` or `&mut self`|
166 /// |`into_`|`self` |
167 /// |`is_` |`&self` or none |
168 /// |`to_` |`&self` |
170 /// **Why is this bad?** Consistency breeds readability. If you follow the
171 /// conventions, your users won't be surprised that they, e.g., need to supply a
172 /// mutable reference to a `as_..` function.
174 /// **Known problems:** None.
180 /// fn as_str(self) -> &'static str {
186 pub WRONG_SELF_CONVENTION,
188 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
191 declare_clippy_lint! {
192 /// **What it does:** This is the same as
193 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
195 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
197 /// **Known problems:** Actually *renaming* the function may break clients if
198 /// the function is part of the public interface. In that case, be mindful of
199 /// the stability guarantees you've given your users.
205 /// pub fn as_str(self) -> &'a str {
210 pub WRONG_PUB_SELF_CONVENTION,
212 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
215 declare_clippy_lint! {
216 /// **What it does:** Checks for usage of `ok().expect(..)`.
218 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
219 /// directly to get a better error message.
221 /// **Known problems:** The error type needs to implement `Debug`
225 /// # let x = Ok::<_, ()>(());
228 /// x.ok().expect("why did I do this again?");
231 /// x.expect("why did I do this again?");
235 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
238 declare_clippy_lint! {
239 /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
240 /// `result.map(_).unwrap_or_else(_)`.
242 /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
243 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
245 /// **Known problems:** The order of the arguments is not in execution order
249 /// # let x = Some(1);
252 /// x.map(|a| a + 1).unwrap_or(0);
255 /// x.map_or(0, |a| a + 1);
261 /// # let x: Result<usize, ()> = Ok(1);
262 /// # fn some_function(foo: ()) -> usize { 1 }
265 /// x.map(|a| a + 1).unwrap_or_else(some_function);
268 /// x.map_or_else(some_function, |a| a + 1);
272 "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)`"
275 declare_clippy_lint! {
276 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
278 /// **Why is this bad?** Readability, this can be written more concisely as
281 /// **Known problems:** The order of the arguments is not in execution order.
285 /// # let opt = Some(1);
288 /// opt.map_or(None, |a| Some(a + 1));
291 /// opt.and_then(|a| Some(a + 1));
293 pub OPTION_MAP_OR_NONE,
295 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
298 declare_clippy_lint! {
299 /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
301 /// **Why is this bad?** Readability, this can be written more concisely as
304 /// **Known problems:** None.
310 /// # let r: Result<u32, &str> = Ok(1);
311 /// assert_eq!(Some(1), r.map_or(None, Some));
316 /// # let r: Result<u32, &str> = Ok(1);
317 /// assert_eq!(Some(1), r.ok());
319 pub RESULT_MAP_OR_INTO_OPTION,
321 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
324 declare_clippy_lint! {
325 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
326 /// `_.or_else(|x| Err(y))`.
328 /// **Why is this bad?** Readability, this can be written more concisely as
329 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
331 /// **Known problems:** None
336 /// # fn opt() -> Option<&'static str> { Some("42") }
337 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
338 /// let _ = opt().and_then(|s| Some(s.len()));
339 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
340 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
343 /// The correct use would be:
346 /// # fn opt() -> Option<&'static str> { Some("42") }
347 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
348 /// let _ = opt().map(|s| s.len());
349 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
350 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
352 pub BIND_INSTEAD_OF_MAP,
354 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
357 declare_clippy_lint! {
358 /// **What it does:** Checks for usage of `_.filter(_).next()`.
360 /// **Why is this bad?** Readability, this can be written more concisely as
363 /// **Known problems:** None.
367 /// # let vec = vec![1];
368 /// vec.iter().filter(|x| **x == 0).next();
370 /// Could be written as
372 /// # let vec = vec![1];
373 /// vec.iter().find(|x| **x == 0);
377 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
380 declare_clippy_lint! {
381 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
383 /// **Why is this bad?** Readability, this can be written more concisely as
384 /// `_.find(!condition)`.
386 /// **Known problems:** None.
390 /// # let vec = vec![1];
391 /// vec.iter().skip_while(|x| **x == 0).next();
393 /// Could be written as
395 /// # let vec = vec![1];
396 /// vec.iter().find(|x| **x != 0);
400 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
403 declare_clippy_lint! {
404 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
406 /// **Why is this bad?** Readability, this can be written more concisely as
409 /// **Known problems:**
413 /// let vec = vec![vec![1]];
416 /// vec.iter().map(|x| x.iter()).flatten();
419 /// vec.iter().flat_map(|x| x.iter());
423 "using combinations of `flatten` and `map` which can usually be written as a single method call"
426 declare_clippy_lint! {
427 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
428 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
430 /// **Why is this bad?** Readability, this can be written more concisely as
431 /// `_.filter_map(_)`.
433 /// **Known problems:** Often requires a condition + Option/Iterator creation
434 /// inside the closure.
438 /// let vec = vec![1];
441 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
444 /// vec.iter().filter_map(|x| if *x == 0 {
452 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
455 declare_clippy_lint! {
456 /// **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply
457 /// as `filter_map(_)`.
459 /// **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and
462 /// **Known problems:** None.
468 /// .filter(|n| n.checked_add(1).is_some())
469 /// .map(|n| n.checked_add(1).unwrap());
474 /// (0_i32..10).filter_map(|n| n.checked_add(1));
476 pub MANUAL_FILTER_MAP,
478 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
481 declare_clippy_lint! {
482 /// **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply
483 /// as `find_map(_)`.
485 /// **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and
488 /// **Known problems:** None.
494 /// .find(|n| n.checked_add(1).is_some())
495 /// .map(|n| n.checked_add(1).unwrap());
500 /// (0_i32..10).find_map(|n| n.checked_add(1));
504 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
507 declare_clippy_lint! {
508 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
510 /// **Why is this bad?** Readability, this can be written more concisely as
513 /// **Known problems:** None
517 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
519 /// Can be written as
522 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
526 "using combination of `filter_map` and `next` which can usually be written as a single method call"
529 declare_clippy_lint! {
530 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
532 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
534 /// **Known problems:** None
538 /// # let iter = vec![vec![0]].into_iter();
539 /// iter.flat_map(|x| x);
541 /// Can be written as
543 /// # let iter = vec![vec![0]].into_iter();
546 pub FLAT_MAP_IDENTITY,
548 "call to `flat_map` where `flatten` is sufficient"
551 declare_clippy_lint! {
552 /// **What it does:** Checks for an iterator or string search (such as `find()`,
553 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
555 /// **Why is this bad?** Readability, this can be written more concisely as
556 /// `_.any(_)` or `_.contains(_)`.
558 /// **Known problems:** None.
562 /// # let vec = vec![1];
563 /// vec.iter().find(|x| **x == 0).is_some();
565 /// Could be written as
567 /// # let vec = vec![1];
568 /// vec.iter().any(|x| *x == 0);
572 "using an iterator or string search followed by `is_some()`, which is more succinctly expressed as a call to `any()` or `contains()`"
575 declare_clippy_lint! {
576 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
577 /// if it starts with a given char.
579 /// **Why is this bad?** Readability, this can be written more concisely as
580 /// `_.starts_with(_)`.
582 /// **Known problems:** None.
586 /// let name = "foo";
587 /// if name.chars().next() == Some('_') {};
589 /// Could be written as
591 /// let name = "foo";
592 /// if name.starts_with('_') {};
596 "using `.chars().next()` to check if a string starts with a char"
599 declare_clippy_lint! {
600 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
601 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
602 /// `unwrap_or_default` instead.
604 /// **Why is this bad?** The function will always be called and potentially
605 /// allocate an object acting as the default.
607 /// **Known problems:** If the function has side-effects, not calling it will
608 /// change the semantic of the program, but you shouldn't rely on that anyway.
612 /// # let foo = Some(String::new());
613 /// foo.unwrap_or(String::new());
615 /// this can instead be written:
617 /// # let foo = Some(String::new());
618 /// foo.unwrap_or_else(String::new);
622 /// # let foo = Some(String::new());
623 /// foo.unwrap_or_default();
627 "using any `*or` method with a function call, which suggests `*or_else`"
630 declare_clippy_lint! {
631 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
632 /// etc., and suggests to use `unwrap_or_else` instead
634 /// **Why is this bad?** The function will always be called.
636 /// **Known problems:** If the function has side-effects, not calling it will
637 /// change the semantics of the program, but you shouldn't rely on that anyway.
641 /// # let foo = Some(String::new());
642 /// # let err_code = "418";
643 /// # let err_msg = "I'm a teapot";
644 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
648 /// # let foo = Some(String::new());
649 /// # let err_code = "418";
650 /// # let err_msg = "I'm a teapot";
651 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
653 /// this can instead be written:
655 /// # let foo = Some(String::new());
656 /// # let err_code = "418";
657 /// # let err_msg = "I'm a teapot";
658 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
662 "using any `expect` method with a function call"
665 declare_clippy_lint! {
666 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
668 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
669 /// generics, not for using the `clone` method on a concrete type.
671 /// **Known problems:** None.
679 "using `clone` on a `Copy` type"
682 declare_clippy_lint! {
683 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
684 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
685 /// function syntax instead (e.g., `Rc::clone(foo)`).
687 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
688 /// can obscure the fact that only the pointer is being cloned, not the underlying
693 /// # use std::rc::Rc;
694 /// let x = Rc::new(1);
702 pub CLONE_ON_REF_PTR,
704 "using 'clone' on a ref-counted pointer"
707 declare_clippy_lint! {
708 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
710 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
711 /// cloning the underlying `T`.
713 /// **Known problems:** None.
720 /// let z = y.clone();
721 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
724 pub CLONE_DOUBLE_REF,
726 "using `clone` on `&&T`"
729 declare_clippy_lint! {
730 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
731 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
733 /// **Why is this bad?** This bypasses the specialized implementation of
734 /// `ToString` and instead goes through the more expensive string formatting
737 /// **Known problems:** None.
741 /// // Generic implementation for `T: Display` is used (slow)
742 /// ["foo", "bar"].iter().map(|s| s.to_string());
744 /// // OK, the specialized impl is used
745 /// ["foo", "bar"].iter().map(|&s| s.to_string());
747 pub INEFFICIENT_TO_STRING,
749 "using `to_string` on `&&T` where `T: ToString`"
752 declare_clippy_lint! {
753 /// **What it does:** Checks for `new` not returning a type that contains `Self`.
755 /// **Why is this bad?** As a convention, `new` methods are used to make a new
756 /// instance of a type.
758 /// **Known problems:** None.
761 /// In an impl block:
764 /// # struct NotAFoo;
766 /// fn new() -> NotAFoo {
776 /// // Bad. The type name must contain `Self`
777 /// fn new() -> Bar {
785 /// # struct FooError;
787 /// // Good. Return type contains `Self`
788 /// fn new() -> Result<Foo, FooError> {
794 /// Or in a trait definition:
796 /// pub trait Trait {
797 /// // Bad. The type name must contain `Self`
803 /// pub trait Trait {
804 /// // Good. Return type contains `Self`
805 /// fn new() -> Self;
810 "not returning type containing `Self` in a `new` method"
813 declare_clippy_lint! {
814 /// **What it does:** Checks for string methods that receive a single-character
815 /// `str` as an argument, e.g., `_.split("x")`.
817 /// **Why is this bad?** Performing these methods using a `char` is faster than
820 /// **Known problems:** Does not catch multi-byte unicode characters.
829 pub SINGLE_CHAR_PATTERN,
831 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
834 declare_clippy_lint! {
835 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
837 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
838 /// actually intend to panic.
840 /// **Known problems:** None.
843 /// ```rust,should_panic
844 /// for x in (0..100).step_by(0) {
848 pub ITERATOR_STEP_BY_ZERO,
850 "using `Iterator::step_by(0)`, which will panic at runtime"
853 declare_clippy_lint! {
854 /// **What it does:** Checks for the use of `iter.nth(0)`.
856 /// **Why is this bad?** `iter.next()` is equivalent to
857 /// `iter.nth(0)`, as they both consume the next element,
858 /// but is more readable.
860 /// **Known problems:** None.
865 /// # use std::collections::HashSet;
867 /// # let mut s = HashSet::new();
869 /// let x = s.iter().nth(0);
872 /// # let mut s = HashSet::new();
874 /// let x = s.iter().next();
878 "replace `iter.nth(0)` with `iter.next()`"
881 declare_clippy_lint! {
882 /// **What it does:** Checks for use of `.iter().nth()` (and the related
883 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
885 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
888 /// **Known problems:** None.
892 /// let some_vec = vec![0, 1, 2, 3];
893 /// let bad_vec = some_vec.iter().nth(3);
894 /// let bad_slice = &some_vec[..].iter().nth(3);
896 /// The correct use would be:
898 /// let some_vec = vec![0, 1, 2, 3];
899 /// let bad_vec = some_vec.get(3);
900 /// let bad_slice = &some_vec[..].get(3);
904 "using `.iter().nth()` on a standard library type with O(1) element access"
907 declare_clippy_lint! {
908 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
910 /// **Why is this bad?** `.nth(x)` is cleaner
912 /// **Known problems:** None.
916 /// let some_vec = vec![0, 1, 2, 3];
917 /// let bad_vec = some_vec.iter().skip(3).next();
918 /// let bad_slice = &some_vec[..].iter().skip(3).next();
920 /// The correct use would be:
922 /// let some_vec = vec![0, 1, 2, 3];
923 /// let bad_vec = some_vec.iter().nth(3);
924 /// let bad_slice = &some_vec[..].iter().nth(3);
928 "using `.skip(x).next()` on an iterator"
931 declare_clippy_lint! {
932 /// **What it does:** Checks for use of `.get().unwrap()` (or
933 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
935 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
938 /// **Known problems:** Not a replacement for error handling: Using either
939 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
940 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
941 /// temporary placeholder for dealing with the `Option` type, then this does
942 /// not mitigate the need for error handling. If there is a chance that `.get()`
943 /// will be `None` in your program, then it is advisable that the `None` case
944 /// is handled in a future refactor instead of using `.unwrap()` or the Index
949 /// let mut some_vec = vec![0, 1, 2, 3];
950 /// let last = some_vec.get(3).unwrap();
951 /// *some_vec.get_mut(0).unwrap() = 1;
953 /// The correct use would be:
955 /// let mut some_vec = vec![0, 1, 2, 3];
956 /// let last = some_vec[3];
961 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
964 declare_clippy_lint! {
965 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
966 /// `&str` or `String`.
968 /// **Why is this bad?** `.push_str(s)` is clearer
970 /// **Known problems:** None.
975 /// let def = String::from("def");
976 /// let mut s = String::new();
977 /// s.extend(abc.chars());
978 /// s.extend(def.chars());
980 /// The correct use would be:
983 /// let def = String::from("def");
984 /// let mut s = String::new();
986 /// s.push_str(&def);
988 pub STRING_EXTEND_CHARS,
990 "using `x.extend(s.chars())` where s is a `&str` or `String`"
993 declare_clippy_lint! {
994 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
997 /// **Why is this bad?** `.to_vec()` is clearer
999 /// **Known problems:** None.
1003 /// let s = [1, 2, 3, 4, 5];
1004 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1006 /// The better use would be:
1008 /// let s = [1, 2, 3, 4, 5];
1009 /// let s2: Vec<isize> = s.to_vec();
1011 pub ITER_CLONED_COLLECT,
1013 "using `.cloned().collect()` on slice to create a `Vec`"
1016 declare_clippy_lint! {
1017 /// **What it does:** Checks for usage of `_.chars().last()` or
1018 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1020 /// **Why is this bad?** Readability, this can be written more concisely as
1021 /// `_.ends_with(_)`.
1023 /// **Known problems:** None.
1027 /// # let name = "_";
1030 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1033 /// name.ends_with('_') || name.ends_with('-');
1037 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1040 declare_clippy_lint! {
1041 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
1042 /// types before and after the call are the same.
1044 /// **Why is this bad?** The call is unnecessary.
1046 /// **Known problems:** None.
1050 /// # fn do_stuff(x: &[i32]) {}
1051 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1052 /// do_stuff(x.as_ref());
1054 /// The correct use would be:
1056 /// # fn do_stuff(x: &[i32]) {}
1057 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1062 "using `as_ref` where the types before and after the call are the same"
1065 declare_clippy_lint! {
1066 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1067 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1068 /// `sum` or `product`.
1070 /// **Why is this bad?** Readability.
1072 /// **Known problems:** None.
1076 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1078 /// This could be written as:
1080 /// let _ = (0..3).any(|x| x > 2);
1082 pub UNNECESSARY_FOLD,
1084 "using `fold` when a more succinct alternative exists"
1087 declare_clippy_lint! {
1088 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1089 /// More specifically it checks if the closure provided is only performing one of the
1090 /// filter or map operations and suggests the appropriate option.
1092 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1093 /// operation is being performed.
1095 /// **Known problems:** None
1099 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1101 /// // As there is no transformation of the argument this could be written as:
1102 /// let _ = (0..3).filter(|&x| x > 2);
1106 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1108 /// // As there is no conditional check on the argument this could be written as:
1109 /// let _ = (0..4).map(|x| x + 1);
1111 pub UNNECESSARY_FILTER_MAP,
1113 "using `filter_map` when a more succinct alternative exists"
1116 declare_clippy_lint! {
1117 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1120 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1121 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1122 /// `iter_mut` directly.
1124 /// **Known problems:** None
1130 /// let _ = (&vec![3, 4, 5]).into_iter();
1133 /// let _ = (&vec![3, 4, 5]).iter();
1135 pub INTO_ITER_ON_REF,
1137 "using `.into_iter()` on a reference"
1140 declare_clippy_lint! {
1141 /// **What it does:** Checks for calls to `map` followed by a `count`.
1143 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1144 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1145 /// drive the iterator to completion, you can just use `for_each` instead.
1147 /// **Known problems:** None
1152 /// let _ = (0..3).map(|x| x + 2).count();
1156 "suspicious usage of map"
1159 declare_clippy_lint! {
1160 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1162 /// **Why is this bad?** For most types, this is undefined behavior.
1164 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1165 /// of `MaybeUninit`. There may be other types that allow uninitialized
1166 /// data, but those are not yet rigorously defined.
1171 /// // Beware the UB
1172 /// use std::mem::MaybeUninit;
1174 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1177 /// Note that the following is OK:
1180 /// use std::mem::MaybeUninit;
1182 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1183 /// MaybeUninit::uninit().assume_init()
1186 pub UNINIT_ASSUMED_INIT,
1188 "`MaybeUninit::uninit().assume_init()`"
1191 declare_clippy_lint! {
1192 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1194 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1199 /// # let y: u32 = 0;
1200 /// # let x: u32 = 100;
1201 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1202 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1205 /// can be written using dedicated methods for saturating addition/subtraction as:
1208 /// # let y: u32 = 0;
1209 /// # let x: u32 = 100;
1210 /// let add = x.saturating_add(y);
1211 /// let sub = x.saturating_sub(y);
1213 pub MANUAL_SATURATING_ARITHMETIC,
1215 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1218 declare_clippy_lint! {
1219 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1220 /// zero-sized types
1222 /// **Why is this bad?** This is a no-op, and likely unintended
1224 /// **Known problems:** None
1228 /// unsafe { (&() as *const ()).offset(1) };
1232 "Check for offset calculations on raw pointers to zero-sized types"
1235 declare_clippy_lint! {
1236 /// **What it does:** Checks for `FileType::is_file()`.
1238 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1239 /// they are testing whether a path is something they can get bytes from. But
1240 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1241 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1247 /// let metadata = std::fs::metadata("foo.txt")?;
1248 /// let filetype = metadata.file_type();
1250 /// if filetype.is_file() {
1253 /// # Ok::<_, std::io::Error>(())
1257 /// should be written as:
1261 /// let metadata = std::fs::metadata("foo.txt")?;
1262 /// let filetype = metadata.file_type();
1264 /// if !filetype.is_dir() {
1267 /// # Ok::<_, std::io::Error>(())
1270 pub FILETYPE_IS_FILE,
1272 "`FileType::is_file` is not recommended to test for readable file type"
1275 declare_clippy_lint! {
1276 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1278 /// **Why is this bad?** Readability, this can be written more concisely as
1281 /// **Known problems:** None.
1285 /// # let opt = Some("".to_string());
1286 /// opt.as_ref().map(String::as_str)
1289 /// Can be written as
1291 /// # let opt = Some("".to_string());
1295 pub OPTION_AS_REF_DEREF,
1297 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1300 declare_clippy_lint! {
1301 /// **What it does:** Checks for usage of `iter().next()` on a Slice or an Array
1303 /// **Why is this bad?** These can be shortened into `.get()`
1305 /// **Known problems:** None.
1309 /// # let a = [1, 2, 3];
1310 /// # let b = vec![1, 2, 3];
1311 /// a[2..].iter().next();
1312 /// b.iter().next();
1314 /// should be written as:
1316 /// # let a = [1, 2, 3];
1317 /// # let b = vec![1, 2, 3];
1321 pub ITER_NEXT_SLICE,
1323 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1326 declare_clippy_lint! {
1327 /// **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal
1328 /// where `push`/`insert` with a `char` would work fine.
1330 /// **Why is this bad?** It's less clear that we are pushing a single character.
1332 /// **Known problems:** None
1336 /// let mut string = String::new();
1337 /// string.insert_str(0, "R");
1338 /// string.push_str("R");
1340 /// Could be written as
1342 /// let mut string = String::new();
1343 /// string.insert(0, 'R');
1344 /// string.push('R');
1346 pub SINGLE_CHAR_ADD_STR,
1348 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1351 declare_clippy_lint! {
1352 /// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1353 /// lazily evaluated closures on `Option` and `Result`.
1355 /// This lint suggests changing the following functions, when eager evaluation results in
1357 /// - `unwrap_or_else` to `unwrap_or`
1358 /// - `and_then` to `and`
1359 /// - `or_else` to `or`
1360 /// - `get_or_insert_with` to `get_or_insert`
1361 /// - `ok_or_else` to `ok_or`
1363 /// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1365 /// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1366 /// side effects. Eagerly evaluating them can change the semantics of the program.
1371 /// // example code where clippy issues a warning
1372 /// let opt: Option<u32> = None;
1374 /// opt.unwrap_or_else(|| 42);
1378 /// let opt: Option<u32> = None;
1380 /// opt.unwrap_or(42);
1382 pub UNNECESSARY_LAZY_EVALUATIONS,
1384 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1387 declare_clippy_lint! {
1388 /// **What it does:** Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1390 /// **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.
1392 /// **Known problems:** None
1397 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1401 /// (0..3).try_for_each(|t| Err(t));
1403 pub MAP_COLLECT_RESULT_UNIT,
1405 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1408 declare_clippy_lint! {
1409 /// **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator`
1412 /// **Why is this bad?** It is recommended style to use collect. See
1413 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1415 /// **Known problems:** None.
1420 /// use std::iter::FromIterator;
1422 /// let five_fives = std::iter::repeat(5).take(5);
1424 /// let v = Vec::from_iter(five_fives);
1426 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1430 /// let five_fives = std::iter::repeat(5).take(5);
1432 /// let v: Vec<i32> = five_fives.collect();
1434 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1436 pub FROM_ITER_INSTEAD_OF_COLLECT,
1438 "use `.collect()` instead of `::from_iter()`"
1441 declare_clippy_lint! {
1442 /// **What it does:** Checks for usage of `inspect().for_each()`.
1444 /// **Why is this bad?** It is the same as performing the computation
1445 /// inside `inspect` at the beginning of the closure in `for_each`.
1447 /// **Known problems:** None.
1452 /// [1,2,3,4,5].iter()
1453 /// .inspect(|&x| println!("inspect the number: {}", x))
1454 /// .for_each(|&x| {
1455 /// assert!(x >= 0);
1458 /// Can be written as
1460 /// [1,2,3,4,5].iter()
1461 /// .for_each(|&x| {
1462 /// println!("inspect the number: {}", x);
1463 /// assert!(x >= 0);
1466 pub INSPECT_FOR_EACH,
1468 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1471 declare_clippy_lint! {
1472 /// **What it does:** Checks for usage of `filter_map(|x| x)`.
1474 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
1476 /// **Known problems:** None.
1481 /// # let iter = vec![Some(1)].into_iter();
1482 /// iter.filter_map(|x| x);
1486 /// # let iter = vec![Some(1)].into_iter();
1489 pub FILTER_MAP_IDENTITY,
1491 "call to `filter_map` where `flatten` is sufficient"
1494 declare_clippy_lint! {
1495 /// **What it does:** Checks for the use of `.bytes().nth()`.
1497 /// **Why is this bad?** `.as_bytes().get()` is more efficient and more
1500 /// **Known problems:** None.
1506 /// let _ = "Hello".bytes().nth(3);
1509 /// let _ = "Hello".as_bytes().get(3);
1513 "replace `.bytes().nth()` with `.as_bytes().get()`"
1516 pub struct Methods {
1517 msrv: Option<RustcVersion>,
1522 pub fn new(msrv: Option<RustcVersion>) -> Self {
1527 impl_lint_pass!(Methods => [
1530 SHOULD_IMPLEMENT_TRAIT,
1531 WRONG_SELF_CONVENTION,
1532 WRONG_PUB_SELF_CONVENTION,
1535 RESULT_MAP_OR_INTO_OPTION,
1537 BIND_INSTEAD_OF_MAP,
1545 INEFFICIENT_TO_STRING,
1547 SINGLE_CHAR_PATTERN,
1548 SINGLE_CHAR_ADD_STR,
1553 FILTER_MAP_IDENTITY,
1559 ITERATOR_STEP_BY_ZERO,
1566 STRING_EXTEND_CHARS,
1567 ITER_CLONED_COLLECT,
1570 UNNECESSARY_FILTER_MAP,
1573 UNINIT_ASSUMED_INIT,
1574 MANUAL_SATURATING_ARITHMETIC,
1577 OPTION_AS_REF_DEREF,
1578 UNNECESSARY_LAZY_EVALUATIONS,
1579 MAP_COLLECT_RESULT_UNIT,
1580 FROM_ITER_INSTEAD_OF_COLLECT,
1584 impl<'tcx> LateLintPass<'tcx> for Methods {
1585 #[allow(clippy::too_many_lines)]
1586 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1587 if in_macro(expr.span) {
1591 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1592 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1593 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1595 match method_names.as_slice() {
1596 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1597 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1598 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1599 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1600 ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1601 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1602 ["unwrap_or_else", "map"] => {
1603 if !lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0], self.msrv.as_ref()) {
1604 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or");
1607 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1608 ["and_then", ..] => {
1609 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
1610 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
1611 if !biom_option_linted && !biom_result_linted {
1612 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "and");
1615 ["or_else", ..] => {
1616 if !bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]) {
1617 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "or");
1620 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1621 ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1622 ["next", "iter"] => lint_iter_next(cx, expr, arg_lists[1]),
1623 ["map", "filter"] => lint_filter_map(cx, expr, false),
1624 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1625 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1], self.msrv.as_ref()),
1626 ["map", "find"] => lint_filter_map(cx, expr, true),
1627 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1628 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1629 ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1630 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1631 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1632 ["is_some", "position"] => {
1633 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1635 ["is_some", "rposition"] => {
1636 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1638 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1639 ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1640 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1641 ["nth", "bytes"] => bytes_nth::lints(cx, expr, &arg_lists[1]),
1642 ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1643 ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1644 ["next", "skip"] => lint_iter_skip_next(cx, expr, arg_lists[1]),
1645 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1646 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1647 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1648 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1649 ["filter_map", ..] => {
1650 unnecessary_filter_map::lint(cx, expr, arg_lists[0]);
1651 filter_map_identity::check(cx, expr, arg_lists[0], method_spans[0]);
1653 ["count", "map"] => lint_suspicious_map(cx, expr),
1654 ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1655 ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
1656 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1658 ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
1659 check_pointer_offset(cx, expr, arg_lists[0])
1661 ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1662 ["map", "as_ref"] => {
1663 lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false, self.msrv.as_ref())
1665 ["map", "as_mut"] => {
1666 lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true, self.msrv.as_ref())
1668 ["unwrap_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or"),
1669 ["get_or_insert_with", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "get_or_insert"),
1670 ["ok_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "ok_or"),
1671 ["collect", "map"] => lint_map_collect(cx, expr, arg_lists[1], arg_lists[0]),
1672 ["for_each", "inspect"] => inspect_for_each::lint(cx, expr, method_spans[1]),
1677 hir::ExprKind::Call(ref func, ref args) => {
1678 if let hir::ExprKind::Path(path) = &func.kind {
1679 if match_qpath(path, &["from_iter"]) {
1680 lint_from_iter(cx, expr, args);
1684 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
1685 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1686 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1688 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
1689 if args.len() == 1 && method_call.ident.name == sym::clone {
1690 lint_clone_on_copy(cx, expr, &args[0], self_ty);
1691 lint_clone_on_ref_ptr(cx, expr, &args[0]);
1693 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1694 inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1697 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
1698 if match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
1699 lint_single_char_push_string(cx, expr, args);
1700 } else if match_def_path(cx, fn_def_id, &paths::INSERT_STR) {
1701 lint_single_char_insert_string(cx, expr, args);
1705 match self_ty.kind() {
1706 ty::Ref(_, ty, _) if *ty.kind() == ty::Str => {
1707 for &(method, pos) in &PATTERN_METHODS {
1708 if method_call.ident.name.as_str() == method && args.len() > pos {
1709 lint_single_char_pattern(cx, expr, &args[pos]);
1713 ty::Ref(..) if method_call.ident.name == sym::into_iter => {
1714 lint_into_iter(cx, expr, self_ty, *method_span);
1719 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1720 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1722 let mut info = BinaryExprInfo {
1726 eq: op.node == hir::BinOpKind::Eq,
1728 lint_binary_expr_with_method_call(cx, &mut info);
1734 #[allow(clippy::too_many_lines)]
1735 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1736 if in_external_macro(cx.sess(), impl_item.span) {
1739 let name = impl_item.ident.name.as_str();
1740 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
1741 let item = cx.tcx.hir().expect_item(parent);
1742 let self_ty = cx.tcx.type_of(item.def_id);
1744 // if this impl block implements a trait, lint in trait definition instead
1745 if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
1750 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1751 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1753 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
1754 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1756 let first_arg_ty = &method_sig.inputs().iter().next();
1758 // check conventions w.r.t. conversion method names and predicates
1759 if let Some(first_arg_ty) = first_arg_ty;
1762 if cx.access_levels.is_exported(impl_item.hir_id()) {
1763 // check missing trait implementations
1764 for method_config in &TRAIT_METHODS {
1765 if name == method_config.method_name &&
1766 sig.decl.inputs.len() == method_config.param_count &&
1767 method_config.output_type.matches(cx, &sig.decl.output) &&
1768 method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1769 fn_header_equals(method_config.fn_header, sig.header) &&
1770 method_config.lifetime_param_cond(&impl_item)
1774 SHOULD_IMPLEMENT_TRAIT,
1777 "method `{}` can be confused for the standard trait method `{}::{}`",
1778 method_config.method_name,
1779 method_config.trait_name,
1780 method_config.method_name
1784 "consider implementing the trait `{}` or choosing a less ambiguous method name",
1785 method_config.trait_name
1792 lint_wrong_self_convention(
1795 item.vis.node.is_pub(),
1803 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1804 let ret_ty = return_ty(cx, impl_item.hir_id());
1806 // walk the return type and check for Self (this does not check associated types)
1807 if contains_ty(ret_ty, self_ty) {
1811 // if return type is impl trait, check the associated types
1812 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
1813 // one of the associated types must be Self
1814 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
1815 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1816 // walk the associated type and check for Self
1817 if contains_ty(projection_predicate.ty, self_ty) {
1824 if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1829 "methods called `new` usually return `Self`",
1835 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1836 if in_external_macro(cx.tcx.sess, item.span) {
1841 if let TraitItemKind::Fn(ref sig, _) = item.kind;
1842 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
1843 let first_arg_span = first_arg_ty.span;
1844 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
1845 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1848 lint_wrong_self_convention(cx, &item.ident.name.as_str(), false, self_ty, first_arg_ty, first_arg_span);
1853 if item.ident.name == sym::new;
1854 if let TraitItemKind::Fn(_, _) = item.kind;
1855 let ret_ty = return_ty(cx, item.hir_id());
1856 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1857 if !contains_ty(ret_ty, self_ty);
1864 "methods called `new` usually return `Self`",
1870 extract_msrv_attr!(LateContext);
1873 fn lint_wrong_self_convention<'tcx>(
1874 cx: &LateContext<'tcx>,
1877 self_ty: &'tcx TyS<'tcx>,
1878 first_arg_ty: &'tcx TyS<'tcx>,
1879 first_arg_span: Span,
1881 let lint = if is_pub {
1882 WRONG_PUB_SELF_CONVENTION
1884 WRONG_SELF_CONVENTION
1886 if let Some((ref conv, self_kinds)) = &CONVENTIONS.iter().find(|(ref conv, _)| conv.check(item_name)) {
1887 if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
1893 "methods called `{}` usually take {}; consider choosing a less ambiguous name",
1897 .map(|k| k.description())
1898 .collect::<Vec<_>>()
1906 /// Checks for the `OR_FUN_CALL` lint.
1907 #[allow(clippy::too_many_lines)]
1908 fn lint_or_fun_call<'tcx>(
1909 cx: &LateContext<'tcx>,
1910 expr: &hir::Expr<'_>,
1913 args: &'tcx [hir::Expr<'_>],
1915 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1916 fn check_unwrap_or_default(
1917 cx: &LateContext<'_>,
1919 fun: &hir::Expr<'_>,
1920 self_expr: &hir::Expr<'_>,
1921 arg: &hir::Expr<'_>,
1927 if name == "unwrap_or";
1928 if let hir::ExprKind::Path(ref qpath) = fun.kind;
1929 let path = &*last_path_segment(qpath).ident.as_str();
1930 if ["default", "new"].contains(&path);
1931 let arg_ty = cx.typeck_results().expr_ty(arg);
1932 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1933 if implements_trait(cx, arg_ty, default_trait_id, &[]);
1936 let mut applicability = Applicability::MachineApplicable;
1941 &format!("use of `{}` followed by a call to `{}`", name, path),
1944 "{}.unwrap_or_default()",
1945 snippet_with_applicability(cx, self_expr.span, "..", &mut applicability)
1957 /// Checks for `*or(foo())`.
1958 #[allow(clippy::too_many_arguments)]
1959 fn check_general_case<'tcx>(
1960 cx: &LateContext<'tcx>,
1963 self_expr: &hir::Expr<'_>,
1964 arg: &'tcx hir::Expr<'_>,
1966 // None if lambda is required
1967 fun_span: Option<Span>,
1969 // (path, fn_has_argument, methods, suffix)
1970 static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [
1971 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1972 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1973 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1974 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1977 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind {
1978 if path.ident.as_str() == "len" {
1979 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
1982 ty::Slice(_) | ty::Array(_, _) => return,
1986 if is_type_diagnostic_item(cx, ty, sym::vec_type) {
1993 if KNOW_TYPES.iter().any(|k| k.2.contains(&name));
1995 if is_lazyness_candidate(cx, arg);
1996 if !contains_return(&arg);
1998 let self_ty = cx.typeck_results().expr_ty(self_expr);
2000 if let Some(&(_, fn_has_arguments, poss, suffix)) =
2001 KNOW_TYPES.iter().find(|&&i| match_type(cx, self_ty, i.0));
2003 if poss.contains(&name);
2006 let sugg: Cow<'_, str> = {
2007 let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) {
2008 (false, Some(fun_span)) => (fun_span, false),
2009 _ => (arg.span, true),
2011 let snippet = snippet_with_macro_callsite(cx, snippet_span, "..");
2013 let l_arg = if fn_has_arguments { "_" } else { "" };
2014 format!("|{}| {}", l_arg, snippet).into()
2019 let span_replace_word = method_span.with_hi(span.hi());
2024 &format!("use of `{}` followed by a function call", name),
2026 format!("{}_{}({})", name, suffix, sugg),
2027 Applicability::HasPlaceholders,
2033 if args.len() == 2 {
2034 match args[1].kind {
2035 hir::ExprKind::Call(ref fun, ref or_args) => {
2036 let or_has_args = !or_args.is_empty();
2037 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
2038 let fun_span = if or_has_args { None } else { Some(fun.span) };
2039 check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, fun_span);
2042 hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => {
2043 check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, None);
2050 /// Checks for the `EXPECT_FUN_CALL` lint.
2051 #[allow(clippy::too_many_lines)]
2052 fn lint_expect_fun_call(
2053 cx: &LateContext<'_>,
2054 expr: &hir::Expr<'_>,
2057 args: &[hir::Expr<'_>],
2059 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
2061 fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
2062 let mut arg_root = arg;
2064 arg_root = match &arg_root.kind {
2065 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
2066 hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
2067 if call_args.len() == 1
2068 && (method_name.ident.name == sym::as_str || method_name.ident.name == sym!(as_ref))
2070 let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
2071 let base_type = arg_type.peel_refs();
2072 *base_type.kind() == ty::Str || is_type_diagnostic_item(cx, base_type, sym::string_type)
2086 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
2087 // converted to string.
2088 fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
2089 let arg_ty = cx.typeck_results().expr_ty(arg);
2090 if is_type_diagnostic_item(cx, arg_ty, sym::string_type) {
2093 if let ty::Ref(_, ty, ..) = arg_ty.kind() {
2094 if *ty.kind() == ty::Str && can_be_static_str(cx, arg) {
2101 // Check if an expression could have type `&'static str`, knowing that it
2102 // has type `&str` for some lifetime.
2103 fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
2105 hir::ExprKind::Lit(_) => true,
2106 hir::ExprKind::Call(fun, _) => {
2107 if let hir::ExprKind::Path(ref p) = fun.kind {
2108 match cx.qpath_res(p, fun.hir_id) {
2109 hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
2110 cx.tcx.fn_sig(def_id).output().skip_binder().kind(),
2111 ty::Ref(ty::ReStatic, ..)
2119 hir::ExprKind::MethodCall(..) => {
2121 .type_dependent_def_id(arg.hir_id)
2122 .map_or(false, |method_id| {
2124 cx.tcx.fn_sig(method_id).output().skip_binder().kind(),
2125 ty::Ref(ty::ReStatic, ..)
2129 hir::ExprKind::Path(ref p) => matches!(
2130 cx.qpath_res(p, arg.hir_id),
2131 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
2137 fn generate_format_arg_snippet(
2138 cx: &LateContext<'_>,
2140 applicability: &mut Applicability,
2143 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
2144 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
2145 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
2150 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
2158 fn is_call(node: &hir::ExprKind<'_>) -> bool {
2160 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
2163 hir::ExprKind::Call(..)
2164 | hir::ExprKind::MethodCall(..)
2165 // These variants are debatable or require further examination
2166 | hir::ExprKind::If(..)
2167 | hir::ExprKind::Match(..)
2168 | hir::ExprKind::Block{ .. } => true,
2173 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
2177 let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
2178 let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym::option_type) {
2180 } else if is_type_diagnostic_item(cx, receiver_type, sym::result_type) {
2186 let arg_root = get_arg_root(cx, &args[1]);
2188 let span_replace_word = method_span.with_hi(expr.span.hi());
2190 let mut applicability = Applicability::MachineApplicable;
2192 //Special handling for `format!` as arg_root
2194 if let hir::ExprKind::Block(block, None) = &arg_root.kind;
2195 if block.stmts.len() == 1;
2196 if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
2197 if let Some(arg_root) = &local.init;
2198 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
2199 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
2200 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
2202 let fmt_spec = &format_args[0];
2203 let fmt_args = &format_args[1];
2205 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
2207 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
2209 let sugg = args.join(", ");
2215 &format!("use of `{}` followed by a function call", name),
2217 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
2225 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
2226 if requires_to_string(cx, arg_root) {
2227 arg_root_snippet.to_mut().push_str(".to_string()");
2234 &format!("use of `{}` followed by a function call", name),
2237 "unwrap_or_else({} {{ panic!(\"{{}}\", {}) }})",
2238 closure_args, arg_root_snippet
2244 /// Checks for the `CLONE_ON_COPY` lint.
2245 fn lint_clone_on_copy(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
2246 let ty = cx.typeck_results().expr_ty(expr);
2247 if let ty::Ref(_, inner, _) = arg_ty.kind() {
2248 if let ty::Ref(_, innermost, _) = inner.kind() {
2254 "using `clone` on a double-reference; \
2255 this will copy the reference of type `{}` instead of cloning the inner type",
2259 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
2260 let mut ty = innermost;
2262 while let ty::Ref(_, inner, _) = ty.kind() {
2266 let refs: String = iter::repeat('&').take(n + 1).collect();
2267 let derefs: String = iter::repeat('*').take(n).collect();
2268 let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
2269 diag.span_suggestion(
2271 "try dereferencing it",
2272 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
2273 Applicability::MaybeIncorrect,
2275 diag.span_suggestion(
2277 "or try being explicit if you are sure, that you want to clone a reference",
2279 Applicability::MaybeIncorrect,
2284 return; // don't report clone_on_copy
2288 if is_copy(cx, ty) {
2290 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
2291 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
2292 match &cx.tcx.hir().get(parent) {
2293 hir::Node::Expr(parent) => match parent.kind {
2294 // &*x is a nop, &x.clone() is not
2295 hir::ExprKind::AddrOf(..) => return,
2296 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
2297 hir::ExprKind::MethodCall(_, _, parent_args, _) if expr.hir_id == parent_args[0].hir_id => {
2303 hir::Node::Stmt(stmt) => {
2304 if let hir::StmtKind::Local(ref loc) = stmt.kind {
2305 if let hir::PatKind::Ref(..) = loc.pat.kind {
2306 // let ref y = *x borrows x, let ref y = x.clone() does not
2314 // x.clone() might have dereferenced x, possibly through Deref impls
2315 if cx.typeck_results().expr_ty(arg) == ty {
2316 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
2318 let deref_count = cx
2320 .expr_adjustments(arg)
2322 .filter(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
2324 let derefs: String = iter::repeat('*').take(deref_count).collect();
2325 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
2334 &format!("using `clone` on type `{}` which implements the `Copy` trait", ty),
2336 if let Some((text, snip)) = snip {
2337 diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable);
2344 fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
2345 let obj_ty = cx.typeck_results().expr_ty(arg).peel_refs();
2347 if let ty::Adt(_, subst) = obj_ty.kind() {
2348 let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
2350 } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
2352 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
2358 let snippet = snippet_with_macro_callsite(cx, arg.span, "..");
2364 "using `.clone()` on a ref-counted pointer",
2366 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
2367 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
2372 fn lint_string_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2374 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2375 let target = &arglists[0][0];
2376 let self_ty = cx.typeck_results().expr_ty(target).peel_refs();
2377 let ref_str = if *self_ty.kind() == ty::Str {
2379 } else if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
2385 let mut applicability = Applicability::MachineApplicable;
2388 STRING_EXTEND_CHARS,
2390 "calling `.extend(_.chars())`",
2393 "{}.push_str({}{})",
2394 snippet_with_applicability(cx, args[0].span, "..", &mut applicability),
2396 snippet_with_applicability(cx, target.span, "..", &mut applicability)
2403 fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2404 let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
2405 if is_type_diagnostic_item(cx, obj_ty, sym::string_type) {
2406 lint_string_extend(cx, expr, args);
2410 fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2412 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type);
2413 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0]));
2414 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2419 ITER_CLONED_COLLECT,
2421 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2424 ".to_vec()".to_string(),
2425 Applicability::MachineApplicable,
2431 fn lint_unnecessary_fold(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2432 fn check_fold_with_op(
2433 cx: &LateContext<'_>,
2434 expr: &hir::Expr<'_>,
2435 fold_args: &[hir::Expr<'_>],
2438 replacement_method_name: &str,
2439 replacement_has_args: bool,
2442 // Extract the body of the closure passed to fold
2443 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2444 let closure_body = cx.tcx.hir().body(body_id);
2445 let closure_expr = remove_blocks(&closure_body.value);
2447 // Check if the closure body is of the form `acc <op> some_expr(x)`
2448 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2449 if bin_op.node == op;
2451 // Extract the names of the two arguments to the closure
2452 if let [param_a, param_b] = closure_body.params;
2453 if let PatKind::Binding(_, first_arg_id, ..) = strip_pat_refs(¶m_a.pat).kind;
2454 if let PatKind::Binding(_, second_arg_id, second_arg_ident, _) = strip_pat_refs(¶m_b.pat).kind;
2456 if path_to_local_id(left_expr, first_arg_id);
2457 if replacement_has_args || path_to_local_id(right_expr, second_arg_id);
2460 let mut applicability = Applicability::MachineApplicable;
2461 let sugg = if replacement_has_args {
2463 "{replacement}(|{s}| {r})",
2464 replacement = replacement_method_name,
2465 s = second_arg_ident,
2466 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2471 replacement = replacement_method_name,
2478 fold_span.with_hi(expr.span.hi()),
2479 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2480 "this `.fold` can be written more succinctly using another method",
2489 // Check that this is a call to Iterator::fold rather than just some function called fold
2490 if !match_trait_method(cx, expr, &paths::ITERATOR) {
2495 fold_args.len() == 3,
2496 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2499 // Check if the first argument to .fold is a suitable literal
2500 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2502 ast::LitKind::Bool(false) => {
2503 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2505 ast::LitKind::Bool(true) => {
2506 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2508 ast::LitKind::Int(0, _) => {
2509 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2511 ast::LitKind::Int(1, _) => {
2512 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2519 fn lint_step_by<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2520 if match_trait_method(cx, expr, &paths::ITERATOR) {
2521 if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &args[1]) {
2524 ITERATOR_STEP_BY_ZERO,
2526 "Iterator::step_by(0) will panic at runtime",
2532 fn lint_iter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2533 let caller_expr = &iter_args[0];
2535 // Skip lint if the `iter().next()` expression is a for loop argument,
2536 // since it is already covered by `&loops::ITER_NEXT_LOOP`
2537 let mut parent_expr_opt = get_parent_expr(cx, expr);
2538 while let Some(parent_expr) = parent_expr_opt {
2539 if higher::for_loop(parent_expr).is_some() {
2542 parent_expr_opt = get_parent_expr(cx, parent_expr);
2545 if derefs_to_slice(cx, caller_expr, cx.typeck_results().expr_ty(caller_expr)).is_some() {
2546 // caller is a Slice
2548 if let hir::ExprKind::Index(ref caller_var, ref index_expr) = &caller_expr.kind;
2549 if let Some(higher::Range { start: Some(start_expr), end: None, limits: ast::RangeLimits::HalfOpen })
2550 = higher::range(index_expr);
2551 if let hir::ExprKind::Lit(ref start_lit) = &start_expr.kind;
2552 if let ast::LitKind::Int(start_idx, _) = start_lit.node;
2554 let mut applicability = Applicability::MachineApplicable;
2559 "using `.iter().next()` on a Slice without end index",
2561 format!("{}.get({})", snippet_with_applicability(cx, caller_var.span, "..", &mut applicability), start_idx),
2566 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(caller_expr), sym::vec_type)
2568 &cx.typeck_results().expr_ty(caller_expr).peel_refs().kind(),
2572 // caller is a Vec or an Array
2573 let mut applicability = Applicability::MachineApplicable;
2578 "using `.iter().next()` on an array",
2582 snippet_with_applicability(cx, caller_expr.span, "..", &mut applicability)
2589 fn lint_iter_nth<'tcx>(
2590 cx: &LateContext<'tcx>,
2591 expr: &hir::Expr<'_>,
2592 nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2595 let iter_args = nth_and_iter_args[1];
2596 let mut_str = if is_mut { "_mut" } else { "" };
2597 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])).is_some() {
2599 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym::vec_type) {
2601 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym::vecdeque_type) {
2604 let nth_args = nth_and_iter_args[0];
2605 lint_iter_nth_zero(cx, expr, &nth_args);
2606 return; // caller is not a type that we want to lint
2613 &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2615 &format!("calling `.get{}()` is both faster and more readable", mut_str),
2619 fn lint_iter_nth_zero<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2621 if match_trait_method(cx, expr, &paths::ITERATOR);
2622 if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &nth_args[1]);
2624 let mut applicability = Applicability::MachineApplicable;
2629 "called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent",
2630 "try calling `.next()` instead of `.nth(0)`",
2631 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2638 fn lint_get_unwrap<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args: &'tcx [hir::Expr<'_>], is_mut: bool) {
2639 // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2640 // because they do not implement `IndexMut`
2641 let mut applicability = Applicability::MachineApplicable;
2642 let expr_ty = cx.typeck_results().expr_ty(&get_args[0]);
2643 let get_args_str = if get_args.len() > 1 {
2644 snippet_with_applicability(cx, get_args[1].span, "..", &mut applicability)
2646 return; // not linting on a .get().unwrap() chain or variant
2649 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2650 needs_ref = get_args_str.parse::<usize>().is_ok();
2652 } else if is_type_diagnostic_item(cx, expr_ty, sym::vec_type) {
2653 needs_ref = get_args_str.parse::<usize>().is_ok();
2655 } else if is_type_diagnostic_item(cx, expr_ty, sym::vecdeque_type) {
2656 needs_ref = get_args_str.parse::<usize>().is_ok();
2658 } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym::hashmap_type) {
2661 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2665 return; // caller is not a type that we want to lint
2668 let mut span = expr.span;
2670 // Handle the case where the result is immediately dereferenced
2671 // by not requiring ref and pulling the dereference into the
2675 if let Some(parent) = get_parent_expr(cx, expr);
2676 if let hir::ExprKind::Unary(hir::UnOp::Deref, _) = parent.kind;
2683 let mut_str = if is_mut { "_mut" } else { "" };
2684 let borrow_str = if !needs_ref {
2697 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2698 mut_str, caller_type
2704 snippet_with_applicability(cx, get_args[0].span, "..", &mut applicability),
2711 fn lint_iter_skip_next(cx: &LateContext<'_>, expr: &hir::Expr<'_>, skip_args: &[hir::Expr<'_>]) {
2712 // lint if caller of skip is an Iterator
2713 if match_trait_method(cx, expr, &paths::ITERATOR) {
2714 if let [caller, n] = skip_args {
2715 let hint = format!(".nth({})", snippet(cx, n.span, ".."));
2719 expr.span.trim_start(caller.span).unwrap(),
2720 "called `skip(..).next()` on an iterator",
2721 "use `nth` instead",
2723 Applicability::MachineApplicable,
2729 fn derefs_to_slice<'tcx>(
2730 cx: &LateContext<'tcx>,
2731 expr: &'tcx hir::Expr<'tcx>,
2733 ) -> Option<&'tcx hir::Expr<'tcx>> {
2734 fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
2736 ty::Slice(_) => true,
2737 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2738 ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type),
2739 ty::Array(_, size) => size
2740 .try_eval_usize(cx.tcx, cx.param_env)
2741 .map_or(false, |size| size < 32),
2742 ty::Ref(_, inner, _) => may_slice(cx, inner),
2747 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
2748 if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
2755 ty::Slice(_) => Some(expr),
2756 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2757 ty::Ref(_, inner, _) => {
2758 if may_slice(cx, inner) {
2769 /// lint use of `unwrap()` for `Option`s and `Result`s
2770 fn lint_unwrap(cx: &LateContext<'_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2771 let obj_ty = cx.typeck_results().expr_ty(&unwrap_args[0]).peel_refs();
2773 let mess = if is_type_diagnostic_item(cx, obj_ty, sym::option_type) {
2774 Some((UNWRAP_USED, "an Option", "None"))
2775 } else if is_type_diagnostic_item(cx, obj_ty, sym::result_type) {
2776 Some((UNWRAP_USED, "a Result", "Err"))
2781 if let Some((lint, kind, none_value)) = mess {
2786 &format!("used `unwrap()` on `{}` value", kind,),
2789 "if you don't want to handle the `{}` case gracefully, consider \
2790 using `expect()` to provide a better panic message",
2797 /// lint use of `expect()` for `Option`s and `Result`s
2798 fn lint_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2799 let obj_ty = cx.typeck_results().expr_ty(&expect_args[0]).peel_refs();
2801 let mess = if is_type_diagnostic_item(cx, obj_ty, sym::option_type) {
2802 Some((EXPECT_USED, "an Option", "None"))
2803 } else if is_type_diagnostic_item(cx, obj_ty, sym::result_type) {
2804 Some((EXPECT_USED, "a Result", "Err"))
2809 if let Some((lint, kind, none_value)) = mess {
2814 &format!("used `expect()` on `{}` value", kind,),
2816 &format!("if this value is an `{}`, it will panic", none_value,),
2821 /// lint use of `ok().expect()` for `Result`s
2822 fn lint_ok_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2824 // lint if the caller of `ok()` is a `Result`
2825 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&ok_args[0]), sym::result_type);
2826 let result_type = cx.typeck_results().expr_ty(&ok_args[0]);
2827 if let Some(error_type) = get_error_type(cx, result_type);
2828 if has_debug_impl(error_type, cx);
2835 "called `ok().expect()` on a `Result` value",
2837 "you can call `expect()` directly on the `Result`",
2843 /// lint use of `map().flatten()` for `Iterators` and 'Options'
2844 fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2845 // lint if caller of `.map().flatten()` is an Iterator
2846 if match_trait_method(cx, expr, &paths::ITERATOR) {
2847 let map_closure_ty = cx.typeck_results().expr_ty(&map_args[1]);
2848 let is_map_to_option = match map_closure_ty.kind() {
2849 ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => {
2850 let map_closure_sig = match map_closure_ty.kind() {
2851 ty::Closure(_, substs) => substs.as_closure().sig(),
2852 _ => map_closure_ty.fn_sig(cx.tcx),
2854 let map_closure_return_ty = cx.tcx.erase_late_bound_regions(map_closure_sig.output());
2855 is_type_diagnostic_item(cx, map_closure_return_ty, sym::option_type)
2860 let method_to_use = if is_map_to_option {
2861 // `(...).map(...)` has type `impl Iterator<Item=Option<...>>
2864 // `(...).map(...)` has type `impl Iterator<Item=impl Iterator<...>>
2867 let func_snippet = snippet(cx, map_args[1].span, "..");
2868 let hint = format!(".{0}({1})", method_to_use, func_snippet);
2872 expr.span.with_lo(map_args[0].span.hi()),
2873 "called `map(..).flatten()` on an `Iterator`",
2874 &format!("try using `{}` instead", method_to_use),
2876 Applicability::MachineApplicable,
2880 // lint if caller of `.map().flatten()` is an Option
2881 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type) {
2882 let func_snippet = snippet(cx, map_args[1].span, "..");
2883 let hint = format!(".and_then({})", func_snippet);
2887 expr.span.with_lo(map_args[0].span.hi()),
2888 "called `map(..).flatten()` on an `Option`",
2889 "try using `and_then` instead",
2891 Applicability::MachineApplicable,
2896 const MAP_UNWRAP_OR_MSRV: RustcVersion = RustcVersion::new(1, 41, 0);
2898 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2899 /// Return true if lint triggered
2900 fn lint_map_unwrap_or_else<'tcx>(
2901 cx: &LateContext<'tcx>,
2902 expr: &'tcx hir::Expr<'_>,
2903 map_args: &'tcx [hir::Expr<'_>],
2904 unwrap_args: &'tcx [hir::Expr<'_>],
2905 msrv: Option<&RustcVersion>,
2907 if !meets_msrv(msrv, &MAP_UNWRAP_OR_MSRV) {
2910 // lint if the caller of `map()` is an `Option`
2911 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type);
2912 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::result_type);
2914 if is_option || is_result {
2915 // Don't make a suggestion that may fail to compile due to mutably borrowing
2916 // the same variable twice.
2917 let map_mutated_vars = mutated_variables(&map_args[0], cx);
2918 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2919 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2920 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2928 let msg = if is_option {
2929 "called `map(<f>).unwrap_or_else(<g>)` on an `Option` value. This can be done more directly by calling \
2930 `map_or_else(<g>, <f>)` instead"
2932 "called `map(<f>).unwrap_or_else(<g>)` on a `Result` value. This can be done more directly by calling \
2933 `.map_or_else(<g>, <f>)` instead"
2935 // get snippets for args to map() and unwrap_or_else()
2936 let map_snippet = snippet(cx, map_args[1].span, "..");
2937 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2938 // lint, with note if neither arg is > 1 line and both map() and
2939 // unwrap_or_else() have the same span
2940 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2941 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2942 if same_span && !multiline {
2943 let var_snippet = snippet(cx, map_args[0].span, "..");
2950 format!("{}.map_or_else({}, {})", var_snippet, unwrap_snippet, map_snippet),
2951 Applicability::MachineApplicable,
2954 } else if same_span && multiline {
2955 span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
2963 /// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
2964 fn lint_map_or_none<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>]) {
2965 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym::option_type);
2966 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym::result_type);
2968 // There are two variants of this `map_or` lint:
2969 // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
2970 // (2) using `map_or` as a combinator instead of `and_then`
2972 // (For this lint) we don't care if any other type calls `map_or`
2973 if !is_option && !is_result {
2977 let (lint_name, msg, instead, hint) = {
2978 let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2979 match_qpath(qpath, &paths::OPTION_NONE)
2984 if !default_arg_is_none {
2989 let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
2990 match_qpath(qpath, &paths::OPTION_SOME)
2996 let self_snippet = snippet(cx, map_or_args[0].span, "..");
2997 let func_snippet = snippet(cx, map_or_args[2].span, "..");
2998 let msg = "called `map_or(None, ..)` on an `Option` value. This can be done more directly by calling \
2999 `and_then(..)` instead";
3003 "try using `and_then` instead",
3004 format!("{0}.and_then({1})", self_snippet, func_snippet),
3006 } else if f_arg_is_some {
3007 let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
3009 let self_snippet = snippet(cx, map_or_args[0].span, "..");
3011 RESULT_MAP_OR_INTO_OPTION,
3013 "try using `ok` instead",
3014 format!("{0}.ok()", self_snippet),
3029 Applicability::MachineApplicable,
3033 /// lint use of `filter().next()` for `Iterators`
3034 fn lint_filter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
3035 // lint if caller of `.filter().next()` is an Iterator
3036 if match_trait_method(cx, expr, &paths::ITERATOR) {
3037 let msg = "called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
3038 `.find(..)` instead.";
3039 let filter_snippet = snippet(cx, filter_args[1].span, "..");
3040 if filter_snippet.lines().count() <= 1 {
3041 let iter_snippet = snippet(cx, filter_args[0].span, "..");
3042 // add note if not multi-line
3049 format!("{}.find({})", iter_snippet, filter_snippet),
3050 Applicability::MachineApplicable,
3053 span_lint(cx, FILTER_NEXT, expr.span, msg);
3058 /// lint use of `skip_while().next()` for `Iterators`
3059 fn lint_skip_while_next<'tcx>(
3060 cx: &LateContext<'tcx>,
3061 expr: &'tcx hir::Expr<'_>,
3062 _skip_while_args: &'tcx [hir::Expr<'_>],
3064 // lint if caller of `.skip_while().next()` is an Iterator
3065 if match_trait_method(cx, expr, &paths::ITERATOR) {
3070 "called `skip_while(<p>).next()` on an `Iterator`",
3072 "this is more succinctly expressed by calling `.find(!<p>)` instead",
3077 /// lint use of `filter().map()` or `find().map()` for `Iterators`
3078 fn lint_filter_map<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, is_find: bool) {
3080 if let ExprKind::MethodCall(_, _, [map_recv, map_arg], map_span) = expr.kind;
3081 if let ExprKind::MethodCall(_, _, [_, filter_arg], filter_span) = map_recv.kind;
3082 if match_trait_method(cx, map_recv, &paths::ITERATOR);
3084 // filter(|x| ...is_some())...
3085 if let ExprKind::Closure(_, _, filter_body_id, ..) = filter_arg.kind;
3086 let filter_body = cx.tcx.hir().body(filter_body_id);
3087 if let [filter_param] = filter_body.params;
3088 // optional ref pattern: `filter(|&x| ..)`
3089 let (filter_pat, is_filter_param_ref) = if let PatKind::Ref(ref_pat, _) = filter_param.pat.kind {
3092 (filter_param.pat, false)
3094 // closure ends with is_some() or is_ok()
3095 if let PatKind::Binding(_, filter_param_id, _, None) = filter_pat.kind;
3096 if let ExprKind::MethodCall(path, _, [filter_arg], _) = filter_body.value.kind;
3097 if let Some(opt_ty) = cx.typeck_results().expr_ty(filter_arg).ty_adt_def();
3098 if let Some(is_result) = if cx.tcx.is_diagnostic_item(sym::option_type, opt_ty.did) {
3100 } else if cx.tcx.is_diagnostic_item(sym::result_type, opt_ty.did) {
3105 if path.ident.name.as_str() == if is_result { "is_ok" } else { "is_some" };
3107 // ...map(|x| ...unwrap())
3108 if let ExprKind::Closure(_, _, map_body_id, ..) = map_arg.kind;
3109 let map_body = cx.tcx.hir().body(map_body_id);
3110 if let [map_param] = map_body.params;
3111 if let PatKind::Binding(_, map_param_id, map_param_ident, None) = map_param.pat.kind;
3112 // closure ends with expect() or unwrap()
3113 if let ExprKind::MethodCall(seg, _, [map_arg, ..], _) = map_body.value.kind;
3114 if matches!(seg.ident.name, sym::expect | sym::unwrap | sym::unwrap_or);
3116 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
3117 // in `filter(|x| ..)`, replace `*x` with `x`
3118 let a_path = if_chain! {
3119 if !is_filter_param_ref;
3120 if let ExprKind::Unary(UnOp::Deref, expr_path) = a.kind;
3121 then { expr_path } else { a }
3123 // let the filter closure arg and the map closure arg be equal
3125 if path_to_local_id(a_path, filter_param_id);
3126 if path_to_local_id(b, map_param_id);
3127 if TyS::same_type(cx.typeck_results().expr_ty_adjusted(a), cx.typeck_results().expr_ty_adjusted(b));
3134 if SpanlessEq::new(cx).expr_fallback(eq_fallback).eq_expr(filter_arg, map_arg);
3136 let span = filter_span.to(map_span);
3137 let (filter_name, lint) = if is_find {
3138 ("find", MANUAL_FIND_MAP)
3140 ("filter", MANUAL_FILTER_MAP)
3142 let msg = format!("`{}(..).map(..)` can be simplified as `{0}_map(..)`", filter_name);
3143 let to_opt = if is_result { ".ok()" } else { "" };
3144 let sugg = format!("{}_map(|{}| {}{})", filter_name, map_param_ident,
3145 snippet(cx, map_arg.span, ".."), to_opt);
3146 span_lint_and_sugg(cx, lint, span, &msg, "try", sugg, Applicability::MachineApplicable);
3151 const FILTER_MAP_NEXT_MSRV: RustcVersion = RustcVersion::new(1, 30, 0);
3153 /// lint use of `filter_map().next()` for `Iterators`
3154 fn lint_filter_map_next<'tcx>(
3155 cx: &LateContext<'tcx>,
3156 expr: &'tcx hir::Expr<'_>,
3157 filter_args: &'tcx [hir::Expr<'_>],
3158 msrv: Option<&RustcVersion>,
3160 if match_trait_method(cx, expr, &paths::ITERATOR) {
3161 if !meets_msrv(msrv, &FILTER_MAP_NEXT_MSRV) {
3165 let msg = "called `filter_map(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
3166 `.find_map(..)` instead.";
3167 let filter_snippet = snippet(cx, filter_args[1].span, "..");
3168 if filter_snippet.lines().count() <= 1 {
3169 let iter_snippet = snippet(cx, filter_args[0].span, "..");
3176 format!("{}.find_map({})", iter_snippet, filter_snippet),
3177 Applicability::MachineApplicable,
3180 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
3185 /// lint use of `filter_map().map()` for `Iterators`
3186 fn lint_filter_map_map<'tcx>(
3187 cx: &LateContext<'tcx>,
3188 expr: &'tcx hir::Expr<'_>,
3189 _filter_args: &'tcx [hir::Expr<'_>],
3190 _map_args: &'tcx [hir::Expr<'_>],
3192 // lint if caller of `.filter_map().map()` is an Iterator
3193 if match_trait_method(cx, expr, &paths::ITERATOR) {
3194 let msg = "called `filter_map(..).map(..)` on an `Iterator`";
3195 let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
3196 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3200 /// lint use of `filter().flat_map()` for `Iterators`
3201 fn lint_filter_flat_map<'tcx>(
3202 cx: &LateContext<'tcx>,
3203 expr: &'tcx hir::Expr<'_>,
3204 _filter_args: &'tcx [hir::Expr<'_>],
3205 _map_args: &'tcx [hir::Expr<'_>],
3207 // lint if caller of `.filter().flat_map()` is an Iterator
3208 if match_trait_method(cx, expr, &paths::ITERATOR) {
3209 let msg = "called `filter(..).flat_map(..)` on an `Iterator`";
3210 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
3211 and filtering by returning `iter::empty()`";
3212 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3216 /// lint use of `filter_map().flat_map()` for `Iterators`
3217 fn lint_filter_map_flat_map<'tcx>(
3218 cx: &LateContext<'tcx>,
3219 expr: &'tcx hir::Expr<'_>,
3220 _filter_args: &'tcx [hir::Expr<'_>],
3221 _map_args: &'tcx [hir::Expr<'_>],
3223 // lint if caller of `.filter_map().flat_map()` is an Iterator
3224 if match_trait_method(cx, expr, &paths::ITERATOR) {
3225 let msg = "called `filter_map(..).flat_map(..)` on an `Iterator`";
3226 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
3227 and filtering by returning `iter::empty()`";
3228 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3232 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
3233 fn lint_flat_map_identity<'tcx>(
3234 cx: &LateContext<'tcx>,
3235 expr: &'tcx hir::Expr<'_>,
3236 flat_map_args: &'tcx [hir::Expr<'_>],
3237 flat_map_span: Span,
3239 if match_trait_method(cx, expr, &paths::ITERATOR) {
3240 let arg_node = &flat_map_args[1].kind;
3242 let apply_lint = |message: &str| {
3246 flat_map_span.with_hi(expr.span.hi()),
3249 "flatten()".to_string(),
3250 Applicability::MachineApplicable,
3255 if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
3256 let body = cx.tcx.hir().body(*body_id);
3258 if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
3259 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
3261 if path.segments.len() == 1;
3262 if path.segments[0].ident.name == binding_ident.name;
3265 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
3270 if let hir::ExprKind::Path(ref qpath) = arg_node;
3272 if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
3275 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
3281 /// lint searching an Iterator followed by `is_some()`
3282 /// or calling `find()` on a string followed by `is_some()`
3283 fn lint_search_is_some<'tcx>(
3284 cx: &LateContext<'tcx>,
3285 expr: &'tcx hir::Expr<'_>,
3286 search_method: &str,
3287 search_args: &'tcx [hir::Expr<'_>],
3288 is_some_args: &'tcx [hir::Expr<'_>],
3291 // lint if caller of search is an Iterator
3292 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
3294 "called `is_some()` after searching an `Iterator` with `{}`",
3297 let hint = "this is more succinctly expressed by calling `any()`";
3298 let search_snippet = snippet(cx, search_args[1].span, "..");
3299 if search_snippet.lines().count() <= 1 {
3300 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
3301 // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
3302 let any_search_snippet = if_chain! {
3303 if search_method == "find";
3304 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
3305 let closure_body = cx.tcx.hir().body(body_id);
3306 if let Some(closure_arg) = closure_body.params.get(0);
3308 if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
3309 Some(search_snippet.replacen('&', "", 1))
3310 } else if let PatKind::Binding(_, _, ident, _) = strip_pat_refs(&closure_arg.pat).kind {
3311 let name = &*ident.name.as_str();
3312 Some(search_snippet.replace(&format!("*{}", name), name))
3320 // add note if not multi-line
3324 method_span.with_hi(expr.span.hi()),
3326 "use `any()` instead",
3329 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
3331 Applicability::MachineApplicable,
3334 span_lint_and_help(cx, SEARCH_IS_SOME, expr.span, &msg, None, hint);
3337 // lint if `find()` is called by `String` or `&str`
3338 else if search_method == "find" {
3339 let is_string_or_str_slice = |e| {
3340 let self_ty = cx.typeck_results().expr_ty(e).peel_refs();
3341 if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
3344 *self_ty.kind() == ty::Str
3348 if is_string_or_str_slice(&search_args[0]);
3349 if is_string_or_str_slice(&search_args[1]);
3351 let msg = "called `is_some()` after calling `find()` on a string";
3352 let mut applicability = Applicability::MachineApplicable;
3353 let find_arg = snippet_with_applicability(cx, search_args[1].span, "..", &mut applicability);
3357 method_span.with_hi(expr.span.hi()),
3359 "use `contains()` instead",
3360 format!("contains({})", find_arg),
3368 /// Used for `lint_binary_expr_with_method_call`.
3369 #[derive(Copy, Clone)]
3370 struct BinaryExprInfo<'a> {
3371 expr: &'a hir::Expr<'a>,
3372 chain: &'a hir::Expr<'a>,
3373 other: &'a hir::Expr<'a>,
3377 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3378 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3379 macro_rules! lint_with_both_lhs_and_rhs {
3380 ($func:ident, $cx:expr, $info:ident) => {
3381 if !$func($cx, $info) {
3382 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3383 if $func($cx, $info) {
3390 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
3391 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
3392 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
3393 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
3396 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3398 cx: &LateContext<'_>,
3399 info: &BinaryExprInfo<'_>,
3400 chain_methods: &[&str],
3401 lint: &'static Lint,
3405 if let Some(args) = method_chain_args(info.chain, chain_methods);
3406 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
3407 if arg_char.len() == 1;
3408 if let hir::ExprKind::Path(ref qpath) = fun.kind;
3409 if let Some(segment) = single_segment_path(qpath);
3410 if segment.ident.name == sym::Some;
3412 let mut applicability = Applicability::MachineApplicable;
3413 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
3415 if *self_ty.kind() != ty::Str {
3423 &format!("you should use the `{}` method", suggest),
3425 format!("{}{}.{}({})",
3426 if info.eq { "" } else { "!" },
3427 snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3429 snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
3440 /// Checks for the `CHARS_NEXT_CMP` lint.
3441 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3442 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
3445 /// Checks for the `CHARS_LAST_CMP` lint.
3446 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3447 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
3450 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
3454 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
3455 fn lint_chars_cmp_with_unwrap<'tcx>(
3456 cx: &LateContext<'tcx>,
3457 info: &BinaryExprInfo<'_>,
3458 chain_methods: &[&str],
3459 lint: &'static Lint,
3463 if let Some(args) = method_chain_args(info.chain, chain_methods);
3464 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
3465 if let ast::LitKind::Char(c) = lit.node;
3467 let mut applicability = Applicability::MachineApplicable;
3472 &format!("you should use the `{}` method", suggest),
3474 format!("{}{}.{}('{}')",
3475 if info.eq { "" } else { "!" },
3476 snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3489 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
3490 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3491 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3494 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3495 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3496 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3499 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3503 fn get_hint_if_single_char_arg(
3504 cx: &LateContext<'_>,
3505 arg: &hir::Expr<'_>,
3506 applicability: &mut Applicability,
3507 ) -> Option<String> {
3509 if let hir::ExprKind::Lit(lit) = &arg.kind;
3510 if let ast::LitKind::Str(r, style) = lit.node;
3511 let string = r.as_str();
3512 if string.chars().count() == 1;
3514 let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
3515 let ch = if let ast::StrStyle::Raw(nhash) = style {
3516 let nhash = nhash as usize;
3517 // for raw string: r##"a"##
3518 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3520 // for regular string: "a"
3521 &snip[1..(snip.len() - 1)]
3523 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3531 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3532 fn lint_single_char_pattern(cx: &LateContext<'_>, _expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
3533 let mut applicability = Applicability::MachineApplicable;
3534 if let Some(hint) = get_hint_if_single_char_arg(cx, arg, &mut applicability) {
3537 SINGLE_CHAR_PATTERN,
3539 "single-character string constant used as pattern",
3540 "try using a `char` instead",
3547 /// lint for length-1 `str`s as argument for `push_str`
3548 fn lint_single_char_push_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3549 let mut applicability = Applicability::MachineApplicable;
3550 if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[1], &mut applicability) {
3551 let base_string_snippet =
3552 snippet_with_applicability(cx, args[0].span.source_callsite(), "..", &mut applicability);
3553 let sugg = format!("{}.push({})", base_string_snippet, extension_string);
3556 SINGLE_CHAR_ADD_STR,
3558 "calling `push_str()` using a single-character string literal",
3559 "consider using `push` with a character literal",
3566 /// lint for length-1 `str`s as argument for `insert_str`
3567 fn lint_single_char_insert_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3568 let mut applicability = Applicability::MachineApplicable;
3569 if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[2], &mut applicability) {
3570 let base_string_snippet =
3571 snippet_with_applicability(cx, args[0].span.source_callsite(), "_", &mut applicability);
3572 let pos_arg = snippet_with_applicability(cx, args[1].span, "..", &mut applicability);
3573 let sugg = format!("{}.insert({}, {})", base_string_snippet, pos_arg, extension_string);
3576 SINGLE_CHAR_ADD_STR,
3578 "calling `insert_str()` using a single-character string literal",
3579 "consider using `insert` with a character literal",
3586 /// Checks for the `USELESS_ASREF` lint.
3587 fn lint_asref(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3588 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3589 // check if the call is to the actual `AsRef` or `AsMut` trait
3590 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3591 // check if the type after `as_ref` or `as_mut` is the same as before
3592 let recvr = &as_ref_args[0];
3593 let rcv_ty = cx.typeck_results().expr_ty(recvr);
3594 let res_ty = cx.typeck_results().expr_ty(expr);
3595 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3596 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3597 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3598 // allow the `as_ref` or `as_mut` if it is followed by another method call
3600 if let Some(parent) = get_parent_expr(cx, expr);
3601 if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind;
3602 if span != &expr.span;
3608 let mut applicability = Applicability::MachineApplicable;
3613 &format!("this call to `{}` does nothing", call_name),
3615 snippet_with_applicability(cx, recvr.span, "..", &mut applicability).to_string(),
3622 fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3623 has_iter_method(cx, self_ref_ty).map(|ty_name| {
3624 let mutbl = match self_ref_ty.kind() {
3625 ty::Ref(_, _, mutbl) => mutbl,
3626 _ => unreachable!(),
3628 let method_name = match mutbl {
3629 hir::Mutability::Not => "iter",
3630 hir::Mutability::Mut => "iter_mut",
3632 (ty_name, method_name)
3636 fn lint_into_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3637 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3640 if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3646 "this `.into_iter()` call is equivalent to `.{}()` and will not consume the `{}`",
3650 method_name.to_string(),
3651 Applicability::MachineApplicable,
3656 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3657 fn lint_maybe_uninit(cx: &LateContext<'_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3659 if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3661 if let hir::ExprKind::Path(ref path) = callee.kind;
3662 if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3663 if !is_maybe_uninit_ty_valid(cx, cx.typeck_results().expr_ty_adjusted(outer));
3667 UNINIT_ASSUMED_INIT,
3669 "this call for this type may be undefined behavior"
3675 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
3677 ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3678 ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3679 ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
3684 fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
3689 "this call to `map()` won't have an effect on the call to `count()`",
3691 "make sure you did not confuse `map` with `filter` or `for_each`",
3695 const OPTION_AS_REF_DEREF_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
3697 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3698 fn lint_option_as_ref_deref<'tcx>(
3699 cx: &LateContext<'tcx>,
3700 expr: &hir::Expr<'_>,
3701 as_ref_args: &[hir::Expr<'_>],
3702 map_args: &[hir::Expr<'_>],
3704 msrv: Option<&RustcVersion>,
3706 if !meets_msrv(msrv, &OPTION_AS_REF_DEREF_MSRV) {
3710 let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
3712 let option_ty = cx.typeck_results().expr_ty(&as_ref_args[0]);
3713 if !is_type_diagnostic_item(cx, option_ty, sym::option_type) {
3717 let deref_aliases: [&[&str]; 9] = [
3718 &paths::DEREF_TRAIT_METHOD,
3719 &paths::DEREF_MUT_TRAIT_METHOD,
3720 &paths::CSTRING_AS_C_STR,
3721 &paths::OS_STRING_AS_OS_STR,
3722 &paths::PATH_BUF_AS_PATH,
3723 &paths::STRING_AS_STR,
3724 &paths::STRING_AS_MUT_STR,
3725 &paths::VEC_AS_SLICE,
3726 &paths::VEC_AS_MUT_SLICE,
3729 let is_deref = match map_args[1].kind {
3730 hir::ExprKind::Path(ref expr_qpath) => cx
3731 .qpath_res(expr_qpath, map_args[1].hir_id)
3733 .map_or(false, |fun_def_id| {
3734 deref_aliases.iter().any(|path| match_def_path(cx, fun_def_id, path))
3736 hir::ExprKind::Closure(_, _, body_id, _, _) => {
3737 let closure_body = cx.tcx.hir().body(body_id);
3738 let closure_expr = remove_blocks(&closure_body.value);
3740 match &closure_expr.kind {
3741 hir::ExprKind::MethodCall(_, _, args, _) => {
3744 if path_to_local_id(&args[0], closure_body.params[0].pat.hir_id);
3747 .expr_adjustments(&args[0])
3750 .collect::<Box<[_]>>();
3751 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3753 let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
3754 deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3760 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
3762 if let hir::ExprKind::Unary(hir::UnOp::Deref, ref inner1) = inner.kind;
3763 if let hir::ExprKind::Unary(hir::UnOp::Deref, ref inner2) = inner1.kind;
3765 path_to_local_id(inner2, closure_body.params[0].pat.hir_id)
3778 let current_method = if is_mut {
3779 format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
3781 format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
3783 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3784 let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3785 let suggestion = format!("try using {} instead", method_hint);
3788 "called `{0}` on an Option value. This can be done more directly \
3789 by calling `{1}` instead",
3790 current_method, hint
3794 OPTION_AS_REF_DEREF,
3799 Applicability::MachineApplicable,
3804 fn lint_map_collect(
3805 cx: &LateContext<'_>,
3806 expr: &hir::Expr<'_>,
3807 map_args: &[hir::Expr<'_>],
3808 collect_args: &[hir::Expr<'_>],
3811 // called on Iterator
3812 if let [map_expr] = collect_args;
3813 if match_trait_method(cx, map_expr, &paths::ITERATOR);
3814 // return of collect `Result<(),_>`
3815 let collect_ret_ty = cx.typeck_results().expr_ty(expr);
3816 if is_type_diagnostic_item(cx, collect_ret_ty, sym::result_type);
3817 if let ty::Adt(_, substs) = collect_ret_ty.kind();
3818 if let Some(result_t) = substs.types().next();
3819 if result_t.is_unit();
3820 // get parts for snippet
3821 if let [iter, map_fn] = map_args;
3825 MAP_COLLECT_RESULT_UNIT,
3827 "`.map().collect()` can be replaced with `.try_for_each()`",
3830 "{}.try_for_each({})",
3831 snippet(cx, iter.span, ".."),
3832 snippet(cx, map_fn.span, "..")
3834 Applicability::MachineApplicable,
3840 /// Given a `Result<T, E>` type, return its error type (`E`).
3841 fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3843 ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym::result_type) => substs.types().nth(1),
3848 /// This checks whether a given type is known to implement Debug.
3849 fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
3851 .get_diagnostic_item(sym::debug_trait)
3852 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3857 StartsWith(&'static str),
3861 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3862 (Convention::Eq("new"), &[SelfKind::No]),
3863 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3864 (Convention::StartsWith("from_"), &[SelfKind::No]),
3865 (Convention::StartsWith("into_"), &[SelfKind::Value]),
3866 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3867 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3868 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3871 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3872 unsafety: hir::Unsafety::Normal,
3873 constness: hir::Constness::NotConst,
3874 asyncness: hir::IsAsync::NotAsync,
3875 abi: rustc_target::spec::abi::Abi::Rust,
3878 struct ShouldImplTraitCase {
3879 trait_name: &'static str,
3880 method_name: &'static str,
3882 fn_header: hir::FnHeader,
3883 // implicit self kind expected (none, self, &self, ...)
3884 self_kind: SelfKind,
3885 // checks against the output type
3886 output_type: OutType,
3887 // certain methods with explicit lifetimes can't implement the equivalent trait method
3888 lint_explicit_lifetime: bool,
3890 impl ShouldImplTraitCase {
3892 trait_name: &'static str,
3893 method_name: &'static str,
3895 fn_header: hir::FnHeader,
3896 self_kind: SelfKind,
3897 output_type: OutType,
3898 lint_explicit_lifetime: bool,
3899 ) -> ShouldImplTraitCase {
3900 ShouldImplTraitCase {
3907 lint_explicit_lifetime,
3911 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3912 self.lint_explicit_lifetime
3913 || !impl_item.generics.params.iter().any(|p| {
3916 hir::GenericParamKind::Lifetime {
3917 kind: hir::LifetimeParamKind::Explicit
3925 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3926 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3927 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3928 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3929 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3930 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3931 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3932 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3933 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3934 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3935 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3936 // FIXME: default doesn't work
3937 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3938 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3939 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3940 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3941 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3942 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3943 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3944 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3945 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3946 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3947 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3948 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3949 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3950 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3951 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3952 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3953 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3954 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3955 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3956 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3960 const PATTERN_METHODS: [(&str, usize); 17] = [
3968 ("split_terminator", 1),
3969 ("rsplit_terminator", 1),
3974 ("match_indices", 1),
3975 ("rmatch_indices", 1),
3976 ("trim_start_matches", 1),
3977 ("trim_end_matches", 1),
3980 #[derive(Clone, Copy, PartialEq, Debug)]
3989 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3990 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3991 if ty == parent_ty {
3993 } else if ty.is_box() {
3994 ty.boxed_ty() == parent_ty
3995 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3996 if let ty::Adt(_, substs) = ty.kind() {
3997 substs.types().next().map_or(false, |t| t == parent_ty)
4006 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
4007 if let ty::Ref(_, t, m) = *ty.kind() {
4008 return m == mutability && t == parent_ty;
4011 let trait_path = match mutability {
4012 hir::Mutability::Not => &paths::ASREF_TRAIT,
4013 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
4016 let trait_def_id = match get_trait_def_id(cx, trait_path) {
4018 None => return false,
4020 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
4024 Self::Value => matches_value(cx, parent_ty, ty),
4025 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
4026 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
4027 Self::No => ty != parent_ty,
4032 fn description(self) -> &'static str {
4034 Self::Value => "self by value",
4035 Self::Ref => "self by reference",
4036 Self::RefMut => "self by mutable reference",
4037 Self::No => "no self",
4044 fn check(&self, other: &str) -> bool {
4046 Self::Eq(this) => this == other,
4047 Self::StartsWith(this) => other.starts_with(this) && this != other,
4052 impl fmt::Display for Convention {
4053 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
4055 Self::Eq(this) => this.fmt(f),
4056 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
4061 #[derive(Clone, Copy)]
4070 fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
4071 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
4073 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
4074 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
4075 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
4076 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
4077 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
4083 fn is_bool(ty: &hir::Ty<'_>) -> bool {
4084 if let hir::TyKind::Path(ref p) = ty.kind {
4085 match_qpath(p, &["bool"])
4091 fn check_pointer_offset(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4094 if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.typeck_results().expr_ty(&args[0]).kind();
4095 if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
4098 span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
4103 fn lint_filetype_is_file(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4104 let ty = cx.typeck_results().expr_ty(&args[0]);
4106 if !match_type(cx, ty, &paths::FILE_TYPE) {
4112 let lint_unary: &str;
4113 let help_unary: &str;
4115 if let Some(parent) = get_parent_expr(cx, expr);
4116 if let hir::ExprKind::Unary(op, _) = parent.kind;
4117 if op == hir::UnOp::Not;
4130 let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
4131 let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
4132 span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
4135 fn lint_from_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4136 let ty = cx.typeck_results().expr_ty(expr);
4137 let arg_ty = cx.typeck_results().expr_ty(&args[0]);
4140 if let Some(from_iter_id) = get_trait_def_id(cx, &paths::FROM_ITERATOR);
4141 if let Some(iter_id) = get_trait_def_id(cx, &paths::ITERATOR);
4143 if implements_trait(cx, ty, from_iter_id, &[]) && implements_trait(cx, arg_ty, iter_id, &[]);
4145 // `expr` implements `FromIterator` trait
4146 let iter_expr = sugg::Sugg::hir(cx, &args[0], "..").maybe_par();
4147 let turbofish = extract_turbofish(cx, expr, ty);
4148 let sugg = format!("{}.collect::<{}>()", iter_expr, turbofish);
4151 FROM_ITER_INSTEAD_OF_COLLECT,
4153 "usage of `FromIterator::from_iter`",
4154 "use `.collect()` instead of `::from_iter()`",
4156 Applicability::MaybeIncorrect,
4162 fn extract_turbofish(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ty: Ty<'tcx>) -> String {
4164 let call_site = expr.span.source_callsite();
4165 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(call_site);
4166 let snippet_split = snippet.split("::").collect::<Vec<_>>();
4167 if let Some((_, elements)) = snippet_split.split_last();
4170 // is there a type specifier? (i.e.: like `<u32>` in `collections::BTreeSet::<u32>::`)
4171 if let Some(type_specifier) = snippet_split.iter().find(|e| e.starts_with('<') && e.ends_with('>')) {
4172 // remove the type specifier from the path elements
4173 let without_ts = elements.iter().filter_map(|e| {
4174 if e == type_specifier { None } else { Some((*e).to_string()) }
4175 }).collect::<Vec<_>>();
4176 // join and add the type specifier at the end (i.e.: `collections::BTreeSet<u32>`)
4177 format!("{}{}", without_ts.join("::"), type_specifier)
4179 // type is not explicitly specified so wildcards are needed
4180 // i.e.: 2 wildcards in `std::collections::BTreeMap<&i32, &char>`
4181 let ty_str = ty.to_string();
4182 let start = ty_str.find('<').unwrap_or(0);
4183 let end = ty_str.find('>').unwrap_or_else(|| ty_str.len());
4184 let nb_wildcard = ty_str[start..end].split(',').count();
4185 let wildcards = format!("_{}", ", _".repeat(nb_wildcard - 1));
4186 format!("{}<{}>", elements.join("::"), wildcards)
4194 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
4195 expected.constness == actual.constness
4196 && expected.unsafety == actual.unsafety
4197 && expected.asyncness == actual.asyncness