1 mod bind_instead_of_map;
2 mod inefficient_to_string;
4 mod manual_saturating_arithmetic;
5 mod option_map_unwrap_or;
6 mod unnecessary_filter_map;
7 mod unnecessary_lazy_eval;
13 use bind_instead_of_map::BindInsteadOfMap;
14 use if_chain::if_chain;
16 use rustc_errors::Applicability;
18 use rustc_hir::def::Res;
19 use rustc_hir::{Expr, ExprKind, PatKind, QPath, TraitItem, TraitItemKind, UnOp};
20 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
21 use rustc_middle::lint::in_external_macro;
22 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
23 use rustc_semver::RustcVersion;
24 use rustc_session::{declare_tool_lint, impl_lint_pass};
25 use rustc_span::source_map::Span;
26 use rustc_span::symbol::{sym, SymbolStr};
27 use rustc_typeck::hir_ty_to_ty;
29 use crate::consts::{constant, Constant};
30 use crate::utils::eager_or_lazy::is_lazyness_candidate;
31 use crate::utils::usage::mutated_variables;
33 contains_return, contains_ty, get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, higher,
34 implements_trait, in_macro, is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
35 match_def_path, match_qpath, match_trait_method, match_type, match_var, meets_msrv, method_calls,
36 method_chain_args, paths, remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability,
37 snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, sugg,
38 walk_ptrs_ty_depth, SpanlessEq,
41 declare_clippy_lint! {
42 /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
44 /// **Why is this bad?** It is better to handle the `None` or `Err` case,
45 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
46 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
47 /// `Allow` by default.
49 /// `result.unwrap()` will let the thread panic on `Err` values.
50 /// Normally, you want to implement more sophisticated error handling,
51 /// and propagate errors upwards with `?` operator.
53 /// Even if you want to panic on errors, not all `Error`s implement good
54 /// messages on display. Therefore, it may be beneficial to look at the places
55 /// where they may get displayed. Activate this lint to do just that.
57 /// **Known problems:** None.
61 /// # let opt = Some(1);
67 /// opt.expect("more helpful message");
73 /// # let res: Result<usize, ()> = Ok(1);
79 /// res.expect("more helpful message");
83 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
86 declare_clippy_lint! {
87 /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
89 /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
90 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
91 /// this lint is `Allow` by default.
93 /// `result.expect()` will let the thread panic on `Err`
94 /// values. Normally, you want to implement more sophisticated error handling,
95 /// and propagate errors upwards with `?` operator.
97 /// **Known problems:** None.
101 /// # let opt = Some(1);
104 /// opt.expect("one");
107 /// let opt = Some(1);
114 /// # let res: Result<usize, ()> = Ok(1);
117 /// res.expect("one");
121 /// # Ok::<(), ()>(())
125 "using `.expect()` on `Result` or `Option`, which might be better handled"
128 declare_clippy_lint! {
129 /// **What it does:** Checks for methods that should live in a trait
130 /// implementation of a `std` trait (see [llogiq's blog
131 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
132 /// information) instead of an inherent implementation.
134 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
135 /// the code, often with very little cost. Also people seeing a `mul(...)`
137 /// may expect `*` to work equally, so you should have good reason to disappoint
140 /// **Known problems:** None.
146 /// fn add(&self, other: &X) -> X {
152 pub SHOULD_IMPLEMENT_TRAIT,
154 "defining a method that should be implementing a std trait"
157 declare_clippy_lint! {
158 /// **What it does:** Checks for methods with certain name prefixes and which
159 /// doesn't match how self is taken. The actual rules are:
161 /// |Prefix |`self` taken |
162 /// |-------|----------------------|
163 /// |`as_` |`&self` or `&mut self`|
165 /// |`into_`|`self` |
166 /// |`is_` |`&self` or none |
167 /// |`to_` |`&self` |
169 /// **Why is this bad?** Consistency breeds readability. If you follow the
170 /// conventions, your users won't be surprised that they, e.g., need to supply a
171 /// mutable reference to a `as_..` function.
173 /// **Known problems:** None.
179 /// fn as_str(self) -> &'static str {
185 pub WRONG_SELF_CONVENTION,
187 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
190 declare_clippy_lint! {
191 /// **What it does:** This is the same as
192 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
194 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
196 /// **Known problems:** Actually *renaming* the function may break clients if
197 /// the function is part of the public interface. In that case, be mindful of
198 /// the stability guarantees you've given your users.
204 /// pub fn as_str(self) -> &'a str {
209 pub WRONG_PUB_SELF_CONVENTION,
211 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
214 declare_clippy_lint! {
215 /// **What it does:** Checks for usage of `ok().expect(..)`.
217 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
218 /// directly to get a better error message.
220 /// **Known problems:** The error type needs to implement `Debug`
224 /// # let x = Ok::<_, ()>(());
227 /// x.ok().expect("why did I do this again?");
230 /// x.expect("why did I do this again?");
234 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
237 declare_clippy_lint! {
238 /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
239 /// `result.map(_).unwrap_or_else(_)`.
241 /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
242 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
244 /// **Known problems:** The order of the arguments is not in execution order
248 /// # let x = Some(1);
251 /// x.map(|a| a + 1).unwrap_or(0);
254 /// x.map_or(0, |a| a + 1);
260 /// # let x: Result<usize, ()> = Ok(1);
261 /// # fn some_function(foo: ()) -> usize { 1 }
264 /// x.map(|a| a + 1).unwrap_or_else(some_function);
267 /// x.map_or_else(some_function, |a| a + 1);
271 "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)`"
274 declare_clippy_lint! {
275 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
277 /// **Why is this bad?** Readability, this can be written more concisely as
280 /// **Known problems:** The order of the arguments is not in execution order.
284 /// # let opt = Some(1);
287 /// opt.map_or(None, |a| Some(a + 1));
290 /// opt.and_then(|a| Some(a + 1));
292 pub OPTION_MAP_OR_NONE,
294 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
297 declare_clippy_lint! {
298 /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
300 /// **Why is this bad?** Readability, this can be written more concisely as
303 /// **Known problems:** None.
309 /// # let r: Result<u32, &str> = Ok(1);
310 /// assert_eq!(Some(1), r.map_or(None, Some));
315 /// # let r: Result<u32, &str> = Ok(1);
316 /// assert_eq!(Some(1), r.ok());
318 pub RESULT_MAP_OR_INTO_OPTION,
320 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
323 declare_clippy_lint! {
324 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
325 /// `_.or_else(|x| Err(y))`.
327 /// **Why is this bad?** Readability, this can be written more concisely as
328 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
330 /// **Known problems:** None
335 /// # fn opt() -> Option<&'static str> { Some("42") }
336 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
337 /// let _ = opt().and_then(|s| Some(s.len()));
338 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
339 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
342 /// The correct use would be:
345 /// # fn opt() -> Option<&'static str> { Some("42") }
346 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
347 /// let _ = opt().map(|s| s.len());
348 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
349 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
351 pub BIND_INSTEAD_OF_MAP,
353 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
356 declare_clippy_lint! {
357 /// **What it does:** Checks for usage of `_.filter(_).next()`.
359 /// **Why is this bad?** Readability, this can be written more concisely as
362 /// **Known problems:** None.
366 /// # let vec = vec![1];
367 /// vec.iter().filter(|x| **x == 0).next();
369 /// Could be written as
371 /// # let vec = vec![1];
372 /// vec.iter().find(|x| **x == 0);
376 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
379 declare_clippy_lint! {
380 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
382 /// **Why is this bad?** Readability, this can be written more concisely as
383 /// `_.find(!condition)`.
385 /// **Known problems:** None.
389 /// # let vec = vec![1];
390 /// vec.iter().skip_while(|x| **x == 0).next();
392 /// Could be written as
394 /// # let vec = vec![1];
395 /// vec.iter().find(|x| **x != 0);
399 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
402 declare_clippy_lint! {
403 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
405 /// **Why is this bad?** Readability, this can be written more concisely as
408 /// **Known problems:**
412 /// let vec = vec![vec![1]];
415 /// vec.iter().map(|x| x.iter()).flatten();
418 /// vec.iter().flat_map(|x| x.iter());
422 "using combinations of `flatten` and `map` which can usually be written as a single method call"
425 declare_clippy_lint! {
426 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
427 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
429 /// **Why is this bad?** Readability, this can be written more concisely as
430 /// `_.filter_map(_)`.
432 /// **Known problems:** Often requires a condition + Option/Iterator creation
433 /// inside the closure.
437 /// let vec = vec![1];
440 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
443 /// vec.iter().filter_map(|x| if *x == 0 {
451 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
454 declare_clippy_lint! {
455 /// **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply
456 /// as `filter_map(_)`.
458 /// **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and
461 /// **Known problems:** None.
467 /// .filter(|n| n.checked_add(1).is_some())
468 /// .map(|n| n.checked_add(1).unwrap());
473 /// (0_i32..10).filter_map(|n| n.checked_add(1));
475 pub MANUAL_FILTER_MAP,
477 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
480 declare_clippy_lint! {
481 /// **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply
482 /// as `find_map(_)`.
484 /// **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and
487 /// **Known problems:** None.
493 /// .find(|n| n.checked_add(1).is_some())
494 /// .map(|n| n.checked_add(1).unwrap());
499 /// (0_i32..10).find_map(|n| n.checked_add(1));
503 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
506 declare_clippy_lint! {
507 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
509 /// **Why is this bad?** Readability, this can be written more concisely as
512 /// **Known problems:** None
516 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
518 /// Can be written as
521 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
525 "using combination of `filter_map` and `next` which can usually be written as a single method call"
528 declare_clippy_lint! {
529 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
531 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
533 /// **Known problems:** None
537 /// # let iter = vec![vec![0]].into_iter();
538 /// iter.flat_map(|x| x);
540 /// Can be written as
542 /// # let iter = vec![vec![0]].into_iter();
545 pub FLAT_MAP_IDENTITY,
547 "call to `flat_map` where `flatten` is sufficient"
550 declare_clippy_lint! {
551 /// **What it does:** Checks for an iterator or string search (such as `find()`,
552 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
554 /// **Why is this bad?** Readability, this can be written more concisely as
555 /// `_.any(_)` or `_.contains(_)`.
557 /// **Known problems:** None.
561 /// # let vec = vec![1];
562 /// vec.iter().find(|x| **x == 0).is_some();
564 /// Could be written as
566 /// # let vec = vec![1];
567 /// vec.iter().any(|x| *x == 0);
571 "using an iterator or string search followed by `is_some()`, which is more succinctly expressed as a call to `any()` or `contains()`"
574 declare_clippy_lint! {
575 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
576 /// if it starts with a given char.
578 /// **Why is this bad?** Readability, this can be written more concisely as
579 /// `_.starts_with(_)`.
581 /// **Known problems:** None.
585 /// let name = "foo";
586 /// if name.chars().next() == Some('_') {};
588 /// Could be written as
590 /// let name = "foo";
591 /// if name.starts_with('_') {};
595 "using `.chars().next()` to check if a string starts with a char"
598 declare_clippy_lint! {
599 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
600 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
601 /// `unwrap_or_default` instead.
603 /// **Why is this bad?** The function will always be called and potentially
604 /// allocate an object acting as the default.
606 /// **Known problems:** If the function has side-effects, not calling it will
607 /// change the semantic of the program, but you shouldn't rely on that anyway.
611 /// # let foo = Some(String::new());
612 /// foo.unwrap_or(String::new());
614 /// this can instead be written:
616 /// # let foo = Some(String::new());
617 /// foo.unwrap_or_else(String::new);
621 /// # let foo = Some(String::new());
622 /// foo.unwrap_or_default();
626 "using any `*or` method with a function call, which suggests `*or_else`"
629 declare_clippy_lint! {
630 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
631 /// etc., and suggests to use `unwrap_or_else` instead
633 /// **Why is this bad?** The function will always be called.
635 /// **Known problems:** If the function has side-effects, not calling it will
636 /// change the semantics of the program, but you shouldn't rely on that anyway.
640 /// # let foo = Some(String::new());
641 /// # let err_code = "418";
642 /// # let err_msg = "I'm a teapot";
643 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
647 /// # let foo = Some(String::new());
648 /// # let err_code = "418";
649 /// # let err_msg = "I'm a teapot";
650 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
652 /// this can instead be written:
654 /// # let foo = Some(String::new());
655 /// # let err_code = "418";
656 /// # let err_msg = "I'm a teapot";
657 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
661 "using any `expect` method with a function call"
664 declare_clippy_lint! {
665 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
667 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
668 /// generics, not for using the `clone` method on a concrete type.
670 /// **Known problems:** None.
678 "using `clone` on a `Copy` type"
681 declare_clippy_lint! {
682 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
683 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
684 /// function syntax instead (e.g., `Rc::clone(foo)`).
686 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
687 /// can obscure the fact that only the pointer is being cloned, not the underlying
692 /// # use std::rc::Rc;
693 /// let x = Rc::new(1);
701 pub CLONE_ON_REF_PTR,
703 "using 'clone' on a ref-counted pointer"
706 declare_clippy_lint! {
707 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
709 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
710 /// cloning the underlying `T`.
712 /// **Known problems:** None.
719 /// let z = y.clone();
720 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
723 pub CLONE_DOUBLE_REF,
725 "using `clone` on `&&T`"
728 declare_clippy_lint! {
729 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
730 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
732 /// **Why is this bad?** This bypasses the specialized implementation of
733 /// `ToString` and instead goes through the more expensive string formatting
736 /// **Known problems:** None.
740 /// // Generic implementation for `T: Display` is used (slow)
741 /// ["foo", "bar"].iter().map(|s| s.to_string());
743 /// // OK, the specialized impl is used
744 /// ["foo", "bar"].iter().map(|&s| s.to_string());
746 pub INEFFICIENT_TO_STRING,
748 "using `to_string` on `&&T` where `T: ToString`"
751 declare_clippy_lint! {
752 /// **What it does:** Checks for `new` not returning a type that contains `Self`.
754 /// **Why is this bad?** As a convention, `new` methods are used to make a new
755 /// instance of a type.
757 /// **Known problems:** None.
760 /// In an impl block:
763 /// # struct NotAFoo;
765 /// fn new() -> NotAFoo {
775 /// // Bad. The type name must contain `Self`
776 /// fn new() -> Bar {
784 /// # struct FooError;
786 /// // Good. Return type contains `Self`
787 /// fn new() -> Result<Foo, FooError> {
793 /// Or in a trait definition:
795 /// pub trait Trait {
796 /// // Bad. The type name must contain `Self`
802 /// pub trait Trait {
803 /// // Good. Return type contains `Self`
804 /// fn new() -> Self;
809 "not returning type containing `Self` in a `new` method"
812 declare_clippy_lint! {
813 /// **What it does:** Checks for string methods that receive a single-character
814 /// `str` as an argument, e.g., `_.split("x")`.
816 /// **Why is this bad?** Performing these methods using a `char` is faster than
819 /// **Known problems:** Does not catch multi-byte unicode characters.
828 pub SINGLE_CHAR_PATTERN,
830 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
833 declare_clippy_lint! {
834 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
836 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
837 /// actually intend to panic.
839 /// **Known problems:** None.
842 /// ```rust,should_panic
843 /// for x in (0..100).step_by(0) {
847 pub ITERATOR_STEP_BY_ZERO,
849 "using `Iterator::step_by(0)`, which will panic at runtime"
852 declare_clippy_lint! {
853 /// **What it does:** Checks for the use of `iter.nth(0)`.
855 /// **Why is this bad?** `iter.next()` is equivalent to
856 /// `iter.nth(0)`, as they both consume the next element,
857 /// but is more readable.
859 /// **Known problems:** None.
864 /// # use std::collections::HashSet;
866 /// # let mut s = HashSet::new();
868 /// let x = s.iter().nth(0);
871 /// # let mut s = HashSet::new();
873 /// let x = s.iter().next();
877 "replace `iter.nth(0)` with `iter.next()`"
880 declare_clippy_lint! {
881 /// **What it does:** Checks for use of `.iter().nth()` (and the related
882 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
884 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
887 /// **Known problems:** None.
891 /// let some_vec = vec![0, 1, 2, 3];
892 /// let bad_vec = some_vec.iter().nth(3);
893 /// let bad_slice = &some_vec[..].iter().nth(3);
895 /// The correct use would be:
897 /// let some_vec = vec![0, 1, 2, 3];
898 /// let bad_vec = some_vec.get(3);
899 /// let bad_slice = &some_vec[..].get(3);
903 "using `.iter().nth()` on a standard library type with O(1) element access"
906 declare_clippy_lint! {
907 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
909 /// **Why is this bad?** `.nth(x)` is cleaner
911 /// **Known problems:** None.
915 /// let some_vec = vec![0, 1, 2, 3];
916 /// let bad_vec = some_vec.iter().skip(3).next();
917 /// let bad_slice = &some_vec[..].iter().skip(3).next();
919 /// The correct use would be:
921 /// let some_vec = vec![0, 1, 2, 3];
922 /// let bad_vec = some_vec.iter().nth(3);
923 /// let bad_slice = &some_vec[..].iter().nth(3);
927 "using `.skip(x).next()` on an iterator"
930 declare_clippy_lint! {
931 /// **What it does:** Checks for use of `.get().unwrap()` (or
932 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
934 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
937 /// **Known problems:** Not a replacement for error handling: Using either
938 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
939 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
940 /// temporary placeholder for dealing with the `Option` type, then this does
941 /// not mitigate the need for error handling. If there is a chance that `.get()`
942 /// will be `None` in your program, then it is advisable that the `None` case
943 /// is handled in a future refactor instead of using `.unwrap()` or the Index
948 /// let mut some_vec = vec![0, 1, 2, 3];
949 /// let last = some_vec.get(3).unwrap();
950 /// *some_vec.get_mut(0).unwrap() = 1;
952 /// The correct use would be:
954 /// let mut some_vec = vec![0, 1, 2, 3];
955 /// let last = some_vec[3];
960 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
963 declare_clippy_lint! {
964 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
965 /// `&str` or `String`.
967 /// **Why is this bad?** `.push_str(s)` is clearer
969 /// **Known problems:** None.
974 /// let def = String::from("def");
975 /// let mut s = String::new();
976 /// s.extend(abc.chars());
977 /// s.extend(def.chars());
979 /// The correct use would be:
982 /// let def = String::from("def");
983 /// let mut s = String::new();
985 /// s.push_str(&def);
987 pub STRING_EXTEND_CHARS,
989 "using `x.extend(s.chars())` where s is a `&str` or `String`"
992 declare_clippy_lint! {
993 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
996 /// **Why is this bad?** `.to_vec()` is clearer
998 /// **Known problems:** None.
1002 /// let s = [1, 2, 3, 4, 5];
1003 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1005 /// The better use would be:
1007 /// let s = [1, 2, 3, 4, 5];
1008 /// let s2: Vec<isize> = s.to_vec();
1010 pub ITER_CLONED_COLLECT,
1012 "using `.cloned().collect()` on slice to create a `Vec`"
1015 declare_clippy_lint! {
1016 /// **What it does:** Checks for usage of `_.chars().last()` or
1017 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1019 /// **Why is this bad?** Readability, this can be written more concisely as
1020 /// `_.ends_with(_)`.
1022 /// **Known problems:** None.
1026 /// # let name = "_";
1029 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1032 /// name.ends_with('_') || name.ends_with('-');
1036 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1039 declare_clippy_lint! {
1040 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
1041 /// types before and after the call are the same.
1043 /// **Why is this bad?** The call is unnecessary.
1045 /// **Known problems:** None.
1049 /// # fn do_stuff(x: &[i32]) {}
1050 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1051 /// do_stuff(x.as_ref());
1053 /// The correct use would be:
1055 /// # fn do_stuff(x: &[i32]) {}
1056 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1061 "using `as_ref` where the types before and after the call are the same"
1064 declare_clippy_lint! {
1065 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1066 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1067 /// `sum` or `product`.
1069 /// **Why is this bad?** Readability.
1071 /// **Known problems:** None.
1075 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1077 /// This could be written as:
1079 /// let _ = (0..3).any(|x| x > 2);
1081 pub UNNECESSARY_FOLD,
1083 "using `fold` when a more succinct alternative exists"
1086 declare_clippy_lint! {
1087 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1088 /// More specifically it checks if the closure provided is only performing one of the
1089 /// filter or map operations and suggests the appropriate option.
1091 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1092 /// operation is being performed.
1094 /// **Known problems:** None
1098 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1100 /// // As there is no transformation of the argument this could be written as:
1101 /// let _ = (0..3).filter(|&x| x > 2);
1105 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1107 /// // As there is no conditional check on the argument this could be written as:
1108 /// let _ = (0..4).map(|x| x + 1);
1110 pub UNNECESSARY_FILTER_MAP,
1112 "using `filter_map` when a more succinct alternative exists"
1115 declare_clippy_lint! {
1116 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1119 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1120 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1121 /// `iter_mut` directly.
1123 /// **Known problems:** None
1129 /// let _ = (&vec![3, 4, 5]).into_iter();
1132 /// let _ = (&vec![3, 4, 5]).iter();
1134 pub INTO_ITER_ON_REF,
1136 "using `.into_iter()` on a reference"
1139 declare_clippy_lint! {
1140 /// **What it does:** Checks for calls to `map` followed by a `count`.
1142 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1143 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1144 /// drive the iterator to completion, you can just use `for_each` instead.
1146 /// **Known problems:** None
1151 /// let _ = (0..3).map(|x| x + 2).count();
1155 "suspicious usage of map"
1158 declare_clippy_lint! {
1159 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1161 /// **Why is this bad?** For most types, this is undefined behavior.
1163 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1164 /// of `MaybeUninit`. There may be other types that allow uninitialized
1165 /// data, but those are not yet rigorously defined.
1170 /// // Beware the UB
1171 /// use std::mem::MaybeUninit;
1173 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1176 /// Note that the following is OK:
1179 /// use std::mem::MaybeUninit;
1181 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1182 /// MaybeUninit::uninit().assume_init()
1185 pub UNINIT_ASSUMED_INIT,
1187 "`MaybeUninit::uninit().assume_init()`"
1190 declare_clippy_lint! {
1191 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1193 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1198 /// # let y: u32 = 0;
1199 /// # let x: u32 = 100;
1200 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1201 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1204 /// can be written using dedicated methods for saturating addition/subtraction as:
1207 /// # let y: u32 = 0;
1208 /// # let x: u32 = 100;
1209 /// let add = x.saturating_add(y);
1210 /// let sub = x.saturating_sub(y);
1212 pub MANUAL_SATURATING_ARITHMETIC,
1214 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1217 declare_clippy_lint! {
1218 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1219 /// zero-sized types
1221 /// **Why is this bad?** This is a no-op, and likely unintended
1223 /// **Known problems:** None
1227 /// unsafe { (&() as *const ()).offset(1) };
1231 "Check for offset calculations on raw pointers to zero-sized types"
1234 declare_clippy_lint! {
1235 /// **What it does:** Checks for `FileType::is_file()`.
1237 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1238 /// they are testing whether a path is something they can get bytes from. But
1239 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1240 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1246 /// let metadata = std::fs::metadata("foo.txt")?;
1247 /// let filetype = metadata.file_type();
1249 /// if filetype.is_file() {
1252 /// # Ok::<_, std::io::Error>(())
1256 /// should be written as:
1260 /// let metadata = std::fs::metadata("foo.txt")?;
1261 /// let filetype = metadata.file_type();
1263 /// if !filetype.is_dir() {
1266 /// # Ok::<_, std::io::Error>(())
1269 pub FILETYPE_IS_FILE,
1271 "`FileType::is_file` is not recommended to test for readable file type"
1274 declare_clippy_lint! {
1275 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1277 /// **Why is this bad?** Readability, this can be written more concisely as
1280 /// **Known problems:** None.
1284 /// # let opt = Some("".to_string());
1285 /// opt.as_ref().map(String::as_str)
1288 /// Can be written as
1290 /// # let opt = Some("".to_string());
1294 pub OPTION_AS_REF_DEREF,
1296 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1299 declare_clippy_lint! {
1300 /// **What it does:** Checks for usage of `iter().next()` on a Slice or an Array
1302 /// **Why is this bad?** These can be shortened into `.get()`
1304 /// **Known problems:** None.
1308 /// # let a = [1, 2, 3];
1309 /// # let b = vec![1, 2, 3];
1310 /// a[2..].iter().next();
1311 /// b.iter().next();
1313 /// should be written as:
1315 /// # let a = [1, 2, 3];
1316 /// # let b = vec![1, 2, 3];
1320 pub ITER_NEXT_SLICE,
1322 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1325 declare_clippy_lint! {
1326 /// **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal
1327 /// where `push`/`insert` with a `char` would work fine.
1329 /// **Why is this bad?** It's less clear that we are pushing a single character.
1331 /// **Known problems:** None
1335 /// let mut string = String::new();
1336 /// string.insert_str(0, "R");
1337 /// string.push_str("R");
1339 /// Could be written as
1341 /// let mut string = String::new();
1342 /// string.insert(0, 'R');
1343 /// string.push('R');
1345 pub SINGLE_CHAR_ADD_STR,
1347 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1350 declare_clippy_lint! {
1351 /// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1352 /// lazily evaluated closures on `Option` and `Result`.
1354 /// This lint suggests changing the following functions, when eager evaluation results in
1356 /// - `unwrap_or_else` to `unwrap_or`
1357 /// - `and_then` to `and`
1358 /// - `or_else` to `or`
1359 /// - `get_or_insert_with` to `get_or_insert`
1360 /// - `ok_or_else` to `ok_or`
1362 /// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1364 /// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1365 /// side effects. Eagerly evaluating them can change the semantics of the program.
1370 /// // example code where clippy issues a warning
1371 /// let opt: Option<u32> = None;
1373 /// opt.unwrap_or_else(|| 42);
1377 /// let opt: Option<u32> = None;
1379 /// opt.unwrap_or(42);
1381 pub UNNECESSARY_LAZY_EVALUATIONS,
1383 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1386 declare_clippy_lint! {
1387 /// **What it does:** Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1389 /// **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.
1391 /// **Known problems:** None
1396 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1400 /// (0..3).try_for_each(|t| Err(t));
1402 pub MAP_COLLECT_RESULT_UNIT,
1404 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1407 declare_clippy_lint! {
1408 /// **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator`
1411 /// **Why is this bad?** It is recommended style to use collect. See
1412 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1414 /// **Known problems:** None.
1419 /// use std::iter::FromIterator;
1421 /// let five_fives = std::iter::repeat(5).take(5);
1423 /// let v = Vec::from_iter(five_fives);
1425 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1429 /// let five_fives = std::iter::repeat(5).take(5);
1431 /// let v: Vec<i32> = five_fives.collect();
1433 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1435 pub FROM_ITER_INSTEAD_OF_COLLECT,
1437 "use `.collect()` instead of `::from_iter()`"
1440 declare_clippy_lint! {
1441 /// **What it does:** Checks for usage of `inspect().for_each()`.
1443 /// **Why is this bad?** It is the same as performing the computation
1444 /// inside `inspect` at the beginning of the closure in `for_each`.
1446 /// **Known problems:** None.
1451 /// [1,2,3,4,5].iter()
1452 /// .inspect(|&x| println!("inspect the number: {}", x))
1453 /// .for_each(|&x| {
1454 /// assert!(x >= 0);
1457 /// Can be written as
1459 /// [1,2,3,4,5].iter()
1460 /// .for_each(|&x| {
1461 /// println!("inspect the number: {}", x);
1462 /// assert!(x >= 0);
1465 pub INSPECT_FOR_EACH,
1467 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1470 pub struct Methods {
1471 msrv: Option<RustcVersion>,
1476 pub fn new(msrv: Option<RustcVersion>) -> Self {
1481 impl_lint_pass!(Methods => [
1484 SHOULD_IMPLEMENT_TRAIT,
1485 WRONG_SELF_CONVENTION,
1486 WRONG_PUB_SELF_CONVENTION,
1489 RESULT_MAP_OR_INTO_OPTION,
1491 BIND_INSTEAD_OF_MAP,
1499 INEFFICIENT_TO_STRING,
1501 SINGLE_CHAR_PATTERN,
1502 SINGLE_CHAR_ADD_STR,
1512 ITERATOR_STEP_BY_ZERO,
1518 STRING_EXTEND_CHARS,
1519 ITER_CLONED_COLLECT,
1522 UNNECESSARY_FILTER_MAP,
1525 UNINIT_ASSUMED_INIT,
1526 MANUAL_SATURATING_ARITHMETIC,
1529 OPTION_AS_REF_DEREF,
1530 UNNECESSARY_LAZY_EVALUATIONS,
1531 MAP_COLLECT_RESULT_UNIT,
1532 FROM_ITER_INSTEAD_OF_COLLECT,
1536 impl<'tcx> LateLintPass<'tcx> for Methods {
1537 #[allow(clippy::too_many_lines)]
1538 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1539 if in_macro(expr.span) {
1543 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1544 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1545 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1547 match method_names.as_slice() {
1548 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1549 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1550 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1551 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1552 ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1553 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1554 ["unwrap_or_else", "map"] => {
1555 if !lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0], self.msrv.as_ref()) {
1556 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or");
1559 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1560 ["and_then", ..] => {
1561 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
1562 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
1563 if !biom_option_linted && !biom_result_linted {
1564 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "and");
1567 ["or_else", ..] => {
1568 if !bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]) {
1569 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "or");
1572 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1573 ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1574 ["next", "iter"] => lint_iter_next(cx, expr, arg_lists[1]),
1575 ["map", "filter"] => lint_filter_map(cx, expr, false),
1576 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1577 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1], self.msrv.as_ref()),
1578 ["map", "find"] => lint_filter_map(cx, expr, true),
1579 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1580 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1581 ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1582 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1583 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1584 ["is_some", "position"] => {
1585 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1587 ["is_some", "rposition"] => {
1588 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1590 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1591 ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1592 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1593 ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1594 ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1595 ["next", "skip"] => lint_iter_skip_next(cx, expr, arg_lists[1]),
1596 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1597 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1598 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1599 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1600 ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
1601 ["count", "map"] => lint_suspicious_map(cx, expr),
1602 ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1603 ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
1604 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1606 ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
1607 check_pointer_offset(cx, expr, arg_lists[0])
1609 ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1610 ["map", "as_ref"] => {
1611 lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false, self.msrv.as_ref())
1613 ["map", "as_mut"] => {
1614 lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true, self.msrv.as_ref())
1616 ["unwrap_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or"),
1617 ["get_or_insert_with", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "get_or_insert"),
1618 ["ok_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "ok_or"),
1619 ["collect", "map"] => lint_map_collect(cx, expr, arg_lists[1], arg_lists[0]),
1620 ["for_each", "inspect"] => inspect_for_each::lint(cx, expr, method_spans[1]),
1625 hir::ExprKind::Call(ref func, ref args) => {
1626 if let hir::ExprKind::Path(path) = &func.kind {
1627 if match_qpath(path, &["from_iter"]) {
1628 lint_from_iter(cx, expr, args);
1632 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
1633 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1634 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1636 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
1637 if args.len() == 1 && method_call.ident.name == sym::clone {
1638 lint_clone_on_copy(cx, expr, &args[0], self_ty);
1639 lint_clone_on_ref_ptr(cx, expr, &args[0]);
1641 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1642 inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1645 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
1646 if match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
1647 lint_single_char_push_string(cx, expr, args);
1648 } else if match_def_path(cx, fn_def_id, &paths::INSERT_STR) {
1649 lint_single_char_insert_string(cx, expr, args);
1653 match self_ty.kind() {
1654 ty::Ref(_, ty, _) if *ty.kind() == ty::Str => {
1655 for &(method, pos) in &PATTERN_METHODS {
1656 if method_call.ident.name.as_str() == method && args.len() > pos {
1657 lint_single_char_pattern(cx, expr, &args[pos]);
1661 ty::Ref(..) if method_call.ident.name == sym::into_iter => {
1662 lint_into_iter(cx, expr, self_ty, *method_span);
1667 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1668 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1670 let mut info = BinaryExprInfo {
1674 eq: op.node == hir::BinOpKind::Eq,
1676 lint_binary_expr_with_method_call(cx, &mut info);
1682 #[allow(clippy::too_many_lines)]
1683 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1684 if in_external_macro(cx.sess(), impl_item.span) {
1687 let name = impl_item.ident.name.as_str();
1688 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
1689 let item = cx.tcx.hir().expect_item(parent);
1690 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1691 let self_ty = cx.tcx.type_of(def_id);
1693 // if this impl block implements a trait, lint in trait definition instead
1694 if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
1699 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1700 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1702 let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
1703 let method_sig = cx.tcx.fn_sig(method_def_id);
1704 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1706 let first_arg_ty = &method_sig.inputs().iter().next();
1708 // check conventions w.r.t. conversion method names and predicates
1709 if let Some(first_arg_ty) = first_arg_ty;
1712 if cx.access_levels.is_exported(impl_item.hir_id) {
1713 // check missing trait implementations
1714 for method_config in &TRAIT_METHODS {
1715 if name == method_config.method_name &&
1716 sig.decl.inputs.len() == method_config.param_count &&
1717 method_config.output_type.matches(cx, &sig.decl.output) &&
1718 method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1719 fn_header_equals(method_config.fn_header, sig.header) &&
1720 method_config.lifetime_param_cond(&impl_item)
1724 SHOULD_IMPLEMENT_TRAIT,
1727 "method `{}` can be confused for the standard trait method `{}::{}`",
1728 method_config.method_name,
1729 method_config.trait_name,
1730 method_config.method_name
1734 "consider implementing the trait `{}` or choosing a less ambiguous method name",
1735 method_config.trait_name
1742 lint_wrong_self_convention(
1745 item.vis.node.is_pub(),
1753 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1754 let ret_ty = return_ty(cx, impl_item.hir_id);
1756 // walk the return type and check for Self (this does not check associated types)
1757 if contains_ty(ret_ty, self_ty) {
1761 // if return type is impl trait, check the associated types
1762 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
1763 // one of the associated types must be Self
1764 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
1765 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1766 // walk the associated type and check for Self
1767 if contains_ty(projection_predicate.ty, self_ty) {
1774 if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1779 "methods called `new` usually return `Self`",
1785 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1786 if in_external_macro(cx.tcx.sess, item.span) {
1791 if let TraitItemKind::Fn(ref sig, _) = item.kind;
1792 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
1793 let first_arg_span = first_arg_ty.span;
1794 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
1795 let self_ty = TraitRef::identity(cx.tcx, item.hir_id.owner.to_def_id()).self_ty();
1798 lint_wrong_self_convention(cx, &item.ident.name.as_str(), false, self_ty, first_arg_ty, first_arg_span);
1803 if item.ident.name == sym::new;
1804 if let TraitItemKind::Fn(_, _) = item.kind;
1805 let ret_ty = return_ty(cx, item.hir_id);
1806 let self_ty = TraitRef::identity(cx.tcx, item.hir_id.owner.to_def_id()).self_ty();
1807 if !contains_ty(ret_ty, self_ty);
1814 "methods called `new` usually return `Self`",
1820 extract_msrv_attr!(LateContext);
1823 fn lint_wrong_self_convention<'tcx>(
1824 cx: &LateContext<'tcx>,
1827 self_ty: &'tcx TyS<'tcx>,
1828 first_arg_ty: &'tcx TyS<'tcx>,
1829 first_arg_span: Span,
1831 let lint = if is_pub {
1832 WRONG_PUB_SELF_CONVENTION
1834 WRONG_SELF_CONVENTION
1836 if let Some((ref conv, self_kinds)) = &CONVENTIONS.iter().find(|(ref conv, _)| conv.check(item_name)) {
1837 if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
1843 "methods called `{}` usually take {}; consider choosing a less ambiguous name",
1847 .map(|k| k.description())
1848 .collect::<Vec<_>>()
1856 /// Checks for the `OR_FUN_CALL` lint.
1857 #[allow(clippy::too_many_lines)]
1858 fn lint_or_fun_call<'tcx>(
1859 cx: &LateContext<'tcx>,
1860 expr: &hir::Expr<'_>,
1863 args: &'tcx [hir::Expr<'_>],
1865 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1866 fn check_unwrap_or_default(
1867 cx: &LateContext<'_>,
1869 fun: &hir::Expr<'_>,
1870 self_expr: &hir::Expr<'_>,
1871 arg: &hir::Expr<'_>,
1877 if name == "unwrap_or";
1878 if let hir::ExprKind::Path(ref qpath) = fun.kind;
1879 let path = &*last_path_segment(qpath).ident.as_str();
1880 if ["default", "new"].contains(&path);
1881 let arg_ty = cx.typeck_results().expr_ty(arg);
1882 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1883 if implements_trait(cx, arg_ty, default_trait_id, &[]);
1886 let mut applicability = Applicability::MachineApplicable;
1891 &format!("use of `{}` followed by a call to `{}`", name, path),
1894 "{}.unwrap_or_default()",
1895 snippet_with_applicability(cx, self_expr.span, "..", &mut applicability)
1907 /// Checks for `*or(foo())`.
1908 #[allow(clippy::too_many_arguments)]
1909 fn check_general_case<'tcx>(
1910 cx: &LateContext<'tcx>,
1913 self_expr: &hir::Expr<'_>,
1914 arg: &'tcx hir::Expr<'_>,
1916 // None if lambda is required
1917 fun_span: Option<Span>,
1919 // (path, fn_has_argument, methods, suffix)
1920 static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [
1921 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1922 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1923 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1924 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1927 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind {
1928 if path.ident.as_str() == "len" {
1929 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
1932 ty::Slice(_) | ty::Array(_, _) => return,
1936 if is_type_diagnostic_item(cx, ty, sym::vec_type) {
1943 if KNOW_TYPES.iter().any(|k| k.2.contains(&name));
1945 if is_lazyness_candidate(cx, arg);
1946 if !contains_return(&arg);
1948 let self_ty = cx.typeck_results().expr_ty(self_expr);
1950 if let Some(&(_, fn_has_arguments, poss, suffix)) =
1951 KNOW_TYPES.iter().find(|&&i| match_type(cx, self_ty, i.0));
1953 if poss.contains(&name);
1956 let sugg: Cow<'_, str> = {
1957 let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) {
1958 (false, Some(fun_span)) => (fun_span, false),
1959 _ => (arg.span, true),
1961 let snippet = snippet_with_macro_callsite(cx, snippet_span, "..");
1963 let l_arg = if fn_has_arguments { "_" } else { "" };
1964 format!("|{}| {}", l_arg, snippet).into()
1969 let span_replace_word = method_span.with_hi(span.hi());
1974 &format!("use of `{}` followed by a function call", name),
1976 format!("{}_{}({})", name, suffix, sugg),
1977 Applicability::HasPlaceholders,
1983 if args.len() == 2 {
1984 match args[1].kind {
1985 hir::ExprKind::Call(ref fun, ref or_args) => {
1986 let or_has_args = !or_args.is_empty();
1987 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1988 let fun_span = if or_has_args { None } else { Some(fun.span) };
1989 check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, fun_span);
1992 hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => {
1993 check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, None);
2000 /// Checks for the `EXPECT_FUN_CALL` lint.
2001 #[allow(clippy::too_many_lines)]
2002 fn lint_expect_fun_call(
2003 cx: &LateContext<'_>,
2004 expr: &hir::Expr<'_>,
2007 args: &[hir::Expr<'_>],
2009 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
2011 fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
2012 let mut arg_root = arg;
2014 arg_root = match &arg_root.kind {
2015 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
2016 hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
2017 if call_args.len() == 1
2018 && (method_name.ident.name == sym::as_str || method_name.ident.name == sym!(as_ref))
2020 let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
2021 let base_type = arg_type.peel_refs();
2022 *base_type.kind() == ty::Str || is_type_diagnostic_item(cx, base_type, sym::string_type)
2036 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
2037 // converted to string.
2038 fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
2039 let arg_ty = cx.typeck_results().expr_ty(arg);
2040 if is_type_diagnostic_item(cx, arg_ty, sym::string_type) {
2043 if let ty::Ref(_, ty, ..) = arg_ty.kind() {
2044 if *ty.kind() == ty::Str && can_be_static_str(cx, arg) {
2051 // Check if an expression could have type `&'static str`, knowing that it
2052 // has type `&str` for some lifetime.
2053 fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
2055 hir::ExprKind::Lit(_) => true,
2056 hir::ExprKind::Call(fun, _) => {
2057 if let hir::ExprKind::Path(ref p) = fun.kind {
2058 match cx.qpath_res(p, fun.hir_id) {
2059 hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
2060 cx.tcx.fn_sig(def_id).output().skip_binder().kind(),
2061 ty::Ref(ty::ReStatic, ..)
2069 hir::ExprKind::MethodCall(..) => {
2071 .type_dependent_def_id(arg.hir_id)
2072 .map_or(false, |method_id| {
2074 cx.tcx.fn_sig(method_id).output().skip_binder().kind(),
2075 ty::Ref(ty::ReStatic, ..)
2079 hir::ExprKind::Path(ref p) => matches!(
2080 cx.qpath_res(p, arg.hir_id),
2081 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
2087 fn generate_format_arg_snippet(
2088 cx: &LateContext<'_>,
2090 applicability: &mut Applicability,
2093 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
2094 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
2095 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
2100 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
2108 fn is_call(node: &hir::ExprKind<'_>) -> bool {
2110 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
2113 hir::ExprKind::Call(..)
2114 | hir::ExprKind::MethodCall(..)
2115 // These variants are debatable or require further examination
2116 | hir::ExprKind::If(..)
2117 | hir::ExprKind::Match(..)
2118 | hir::ExprKind::Block{ .. } => true,
2123 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
2127 let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
2128 let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym::option_type) {
2130 } else if is_type_diagnostic_item(cx, receiver_type, sym::result_type) {
2136 let arg_root = get_arg_root(cx, &args[1]);
2138 let span_replace_word = method_span.with_hi(expr.span.hi());
2140 let mut applicability = Applicability::MachineApplicable;
2142 //Special handling for `format!` as arg_root
2144 if let hir::ExprKind::Block(block, None) = &arg_root.kind;
2145 if block.stmts.len() == 1;
2146 if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
2147 if let Some(arg_root) = &local.init;
2148 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
2149 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
2150 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
2152 let fmt_spec = &format_args[0];
2153 let fmt_args = &format_args[1];
2155 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
2157 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
2159 let sugg = args.join(", ");
2165 &format!("use of `{}` followed by a function call", name),
2167 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
2175 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
2176 if requires_to_string(cx, arg_root) {
2177 arg_root_snippet.to_mut().push_str(".to_string()");
2184 &format!("use of `{}` followed by a function call", name),
2186 format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
2191 /// Checks for the `CLONE_ON_COPY` lint.
2192 fn lint_clone_on_copy(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
2193 let ty = cx.typeck_results().expr_ty(expr);
2194 if let ty::Ref(_, inner, _) = arg_ty.kind() {
2195 if let ty::Ref(_, innermost, _) = inner.kind() {
2201 "using `clone` on a double-reference; \
2202 this will copy the reference of type `{}` instead of cloning the inner type",
2206 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
2207 let mut ty = innermost;
2209 while let ty::Ref(_, inner, _) = ty.kind() {
2213 let refs: String = iter::repeat('&').take(n + 1).collect();
2214 let derefs: String = iter::repeat('*').take(n).collect();
2215 let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
2216 diag.span_suggestion(
2218 "try dereferencing it",
2219 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
2220 Applicability::MaybeIncorrect,
2222 diag.span_suggestion(
2224 "or try being explicit if you are sure, that you want to clone a reference",
2226 Applicability::MaybeIncorrect,
2231 return; // don't report clone_on_copy
2235 if is_copy(cx, ty) {
2237 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
2238 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
2239 match &cx.tcx.hir().get(parent) {
2240 hir::Node::Expr(parent) => match parent.kind {
2241 // &*x is a nop, &x.clone() is not
2242 hir::ExprKind::AddrOf(..) => return,
2243 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
2244 hir::ExprKind::MethodCall(_, _, parent_args, _) if expr.hir_id == parent_args[0].hir_id => {
2250 hir::Node::Stmt(stmt) => {
2251 if let hir::StmtKind::Local(ref loc) = stmt.kind {
2252 if let hir::PatKind::Ref(..) = loc.pat.kind {
2253 // let ref y = *x borrows x, let ref y = x.clone() does not
2261 // x.clone() might have dereferenced x, possibly through Deref impls
2262 if cx.typeck_results().expr_ty(arg) == ty {
2263 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
2265 let deref_count = cx
2267 .expr_adjustments(arg)
2269 .filter(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
2271 let derefs: String = iter::repeat('*').take(deref_count).collect();
2272 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
2281 &format!("using `clone` on type `{}` which implements the `Copy` trait", ty),
2283 if let Some((text, snip)) = snip {
2284 diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable);
2291 fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
2292 let obj_ty = cx.typeck_results().expr_ty(arg).peel_refs();
2294 if let ty::Adt(_, subst) = obj_ty.kind() {
2295 let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
2297 } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
2299 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
2305 let snippet = snippet_with_macro_callsite(cx, arg.span, "..");
2311 "using `.clone()` on a ref-counted pointer",
2313 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
2314 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
2319 fn lint_string_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2321 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2322 let target = &arglists[0][0];
2323 let self_ty = cx.typeck_results().expr_ty(target).peel_refs();
2324 let ref_str = if *self_ty.kind() == ty::Str {
2326 } else if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
2332 let mut applicability = Applicability::MachineApplicable;
2335 STRING_EXTEND_CHARS,
2337 "calling `.extend(_.chars())`",
2340 "{}.push_str({}{})",
2341 snippet_with_applicability(cx, args[0].span, "..", &mut applicability),
2343 snippet_with_applicability(cx, target.span, "..", &mut applicability)
2350 fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2351 let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
2352 if is_type_diagnostic_item(cx, obj_ty, sym::string_type) {
2353 lint_string_extend(cx, expr, args);
2357 fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2359 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type);
2360 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0]));
2361 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2366 ITER_CLONED_COLLECT,
2368 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2371 ".to_vec()".to_string(),
2372 Applicability::MachineApplicable,
2378 fn lint_unnecessary_fold(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2379 fn check_fold_with_op(
2380 cx: &LateContext<'_>,
2381 expr: &hir::Expr<'_>,
2382 fold_args: &[hir::Expr<'_>],
2385 replacement_method_name: &str,
2386 replacement_has_args: bool,
2389 // Extract the body of the closure passed to fold
2390 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2391 let closure_body = cx.tcx.hir().body(body_id);
2392 let closure_expr = remove_blocks(&closure_body.value);
2394 // Check if the closure body is of the form `acc <op> some_expr(x)`
2395 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2396 if bin_op.node == op;
2398 // Extract the names of the two arguments to the closure
2399 if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2400 if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2402 if match_var(&*left_expr, first_arg_ident);
2403 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2406 let mut applicability = Applicability::MachineApplicable;
2407 let sugg = if replacement_has_args {
2409 "{replacement}(|{s}| {r})",
2410 replacement = replacement_method_name,
2411 s = second_arg_ident,
2412 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2417 replacement = replacement_method_name,
2424 fold_span.with_hi(expr.span.hi()),
2425 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2426 "this `.fold` can be written more succinctly using another method",
2435 // Check that this is a call to Iterator::fold rather than just some function called fold
2436 if !match_trait_method(cx, expr, &paths::ITERATOR) {
2441 fold_args.len() == 3,
2442 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2445 // Check if the first argument to .fold is a suitable literal
2446 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2448 ast::LitKind::Bool(false) => {
2449 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2451 ast::LitKind::Bool(true) => {
2452 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2454 ast::LitKind::Int(0, _) => {
2455 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2457 ast::LitKind::Int(1, _) => {
2458 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2465 fn lint_step_by<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2466 if match_trait_method(cx, expr, &paths::ITERATOR) {
2467 if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &args[1]) {
2470 ITERATOR_STEP_BY_ZERO,
2472 "Iterator::step_by(0) will panic at runtime",
2478 fn lint_iter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2479 let caller_expr = &iter_args[0];
2481 // Skip lint if the `iter().next()` expression is a for loop argument,
2482 // since it is already covered by `&loops::ITER_NEXT_LOOP`
2483 let mut parent_expr_opt = get_parent_expr(cx, expr);
2484 while let Some(parent_expr) = parent_expr_opt {
2485 if higher::for_loop(parent_expr).is_some() {
2488 parent_expr_opt = get_parent_expr(cx, parent_expr);
2491 if derefs_to_slice(cx, caller_expr, cx.typeck_results().expr_ty(caller_expr)).is_some() {
2492 // caller is a Slice
2494 if let hir::ExprKind::Index(ref caller_var, ref index_expr) = &caller_expr.kind;
2495 if let Some(higher::Range { start: Some(start_expr), end: None, limits: ast::RangeLimits::HalfOpen })
2496 = higher::range(index_expr);
2497 if let hir::ExprKind::Lit(ref start_lit) = &start_expr.kind;
2498 if let ast::LitKind::Int(start_idx, _) = start_lit.node;
2500 let mut applicability = Applicability::MachineApplicable;
2505 "using `.iter().next()` on a Slice without end index",
2507 format!("{}.get({})", snippet_with_applicability(cx, caller_var.span, "..", &mut applicability), start_idx),
2512 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(caller_expr), sym::vec_type)
2514 &cx.typeck_results().expr_ty(caller_expr).peel_refs().kind(),
2518 // caller is a Vec or an Array
2519 let mut applicability = Applicability::MachineApplicable;
2524 "using `.iter().next()` on an array",
2528 snippet_with_applicability(cx, caller_expr.span, "..", &mut applicability)
2535 fn lint_iter_nth<'tcx>(
2536 cx: &LateContext<'tcx>,
2537 expr: &hir::Expr<'_>,
2538 nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2541 let iter_args = nth_and_iter_args[1];
2542 let mut_str = if is_mut { "_mut" } else { "" };
2543 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])).is_some() {
2545 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym::vec_type) {
2547 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vecdeque_type)) {
2550 let nth_args = nth_and_iter_args[0];
2551 lint_iter_nth_zero(cx, expr, &nth_args);
2552 return; // caller is not a type that we want to lint
2559 &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2561 &format!("calling `.get{}()` is both faster and more readable", mut_str),
2565 fn lint_iter_nth_zero<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2567 if match_trait_method(cx, expr, &paths::ITERATOR);
2568 if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &nth_args[1]);
2570 let mut applicability = Applicability::MachineApplicable;
2575 "called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent",
2576 "try calling `.next()` instead of `.nth(0)`",
2577 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2584 fn lint_get_unwrap<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args: &'tcx [hir::Expr<'_>], is_mut: bool) {
2585 // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2586 // because they do not implement `IndexMut`
2587 let mut applicability = Applicability::MachineApplicable;
2588 let expr_ty = cx.typeck_results().expr_ty(&get_args[0]);
2589 let get_args_str = if get_args.len() > 1 {
2590 snippet_with_applicability(cx, get_args[1].span, "..", &mut applicability)
2592 return; // not linting on a .get().unwrap() chain or variant
2595 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2596 needs_ref = get_args_str.parse::<usize>().is_ok();
2598 } else if is_type_diagnostic_item(cx, expr_ty, sym::vec_type) {
2599 needs_ref = get_args_str.parse::<usize>().is_ok();
2601 } else if is_type_diagnostic_item(cx, expr_ty, sym!(vecdeque_type)) {
2602 needs_ref = get_args_str.parse::<usize>().is_ok();
2604 } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym!(hashmap_type)) {
2607 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2611 return; // caller is not a type that we want to lint
2614 let mut span = expr.span;
2616 // Handle the case where the result is immediately dereferenced
2617 // by not requiring ref and pulling the dereference into the
2621 if let Some(parent) = get_parent_expr(cx, expr);
2622 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2629 let mut_str = if is_mut { "_mut" } else { "" };
2630 let borrow_str = if !needs_ref {
2643 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2644 mut_str, caller_type
2650 snippet_with_applicability(cx, get_args[0].span, "..", &mut applicability),
2657 fn lint_iter_skip_next(cx: &LateContext<'_>, expr: &hir::Expr<'_>, skip_args: &[hir::Expr<'_>]) {
2658 // lint if caller of skip is an Iterator
2659 if match_trait_method(cx, expr, &paths::ITERATOR) {
2660 if let [caller, n] = skip_args {
2661 let hint = format!(".nth({})", snippet(cx, n.span, ".."));
2665 expr.span.trim_start(caller.span).unwrap(),
2666 "called `skip(..).next()` on an iterator",
2667 "use `nth` instead",
2669 Applicability::MachineApplicable,
2675 fn derefs_to_slice<'tcx>(
2676 cx: &LateContext<'tcx>,
2677 expr: &'tcx hir::Expr<'tcx>,
2679 ) -> Option<&'tcx hir::Expr<'tcx>> {
2680 fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
2682 ty::Slice(_) => true,
2683 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2684 ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type),
2685 ty::Array(_, size) => size
2686 .try_eval_usize(cx.tcx, cx.param_env)
2687 .map_or(false, |size| size < 32),
2688 ty::Ref(_, inner, _) => may_slice(cx, inner),
2693 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
2694 if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
2701 ty::Slice(_) => Some(expr),
2702 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2703 ty::Ref(_, inner, _) => {
2704 if may_slice(cx, inner) {
2715 /// lint use of `unwrap()` for `Option`s and `Result`s
2716 fn lint_unwrap(cx: &LateContext<'_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2717 let obj_ty = cx.typeck_results().expr_ty(&unwrap_args[0]).peel_refs();
2719 let mess = if is_type_diagnostic_item(cx, obj_ty, sym::option_type) {
2720 Some((UNWRAP_USED, "an Option", "None"))
2721 } else if is_type_diagnostic_item(cx, obj_ty, sym::result_type) {
2722 Some((UNWRAP_USED, "a Result", "Err"))
2727 if let Some((lint, kind, none_value)) = mess {
2732 &format!("used `unwrap()` on `{}` value", kind,),
2735 "if you don't want to handle the `{}` case gracefully, consider \
2736 using `expect()` to provide a better panic message",
2743 /// lint use of `expect()` for `Option`s and `Result`s
2744 fn lint_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2745 let obj_ty = cx.typeck_results().expr_ty(&expect_args[0]).peel_refs();
2747 let mess = if is_type_diagnostic_item(cx, obj_ty, sym::option_type) {
2748 Some((EXPECT_USED, "an Option", "None"))
2749 } else if is_type_diagnostic_item(cx, obj_ty, sym::result_type) {
2750 Some((EXPECT_USED, "a Result", "Err"))
2755 if let Some((lint, kind, none_value)) = mess {
2760 &format!("used `expect()` on `{}` value", kind,),
2762 &format!("if this value is an `{}`, it will panic", none_value,),
2767 /// lint use of `ok().expect()` for `Result`s
2768 fn lint_ok_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2770 // lint if the caller of `ok()` is a `Result`
2771 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&ok_args[0]), sym::result_type);
2772 let result_type = cx.typeck_results().expr_ty(&ok_args[0]);
2773 if let Some(error_type) = get_error_type(cx, result_type);
2774 if has_debug_impl(error_type, cx);
2781 "called `ok().expect()` on a `Result` value",
2783 "you can call `expect()` directly on the `Result`",
2789 /// lint use of `map().flatten()` for `Iterators` and 'Options'
2790 fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2791 // lint if caller of `.map().flatten()` is an Iterator
2792 if match_trait_method(cx, expr, &paths::ITERATOR) {
2793 let map_closure_ty = cx.typeck_results().expr_ty(&map_args[1]);
2794 let is_map_to_option = match map_closure_ty.kind() {
2795 ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => {
2796 let map_closure_sig = match map_closure_ty.kind() {
2797 ty::Closure(_, substs) => substs.as_closure().sig(),
2798 _ => map_closure_ty.fn_sig(cx.tcx),
2800 let map_closure_return_ty = cx.tcx.erase_late_bound_regions(map_closure_sig.output());
2801 is_type_diagnostic_item(cx, map_closure_return_ty, sym::option_type)
2806 let method_to_use = if is_map_to_option {
2807 // `(...).map(...)` has type `impl Iterator<Item=Option<...>>
2810 // `(...).map(...)` has type `impl Iterator<Item=impl Iterator<...>>
2813 let func_snippet = snippet(cx, map_args[1].span, "..");
2814 let hint = format!(".{0}({1})", method_to_use, func_snippet);
2818 expr.span.with_lo(map_args[0].span.hi()),
2819 "called `map(..).flatten()` on an `Iterator`",
2820 &format!("try using `{}` instead", method_to_use),
2822 Applicability::MachineApplicable,
2826 // lint if caller of `.map().flatten()` is an Option
2827 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type) {
2828 let func_snippet = snippet(cx, map_args[1].span, "..");
2829 let hint = format!(".and_then({})", func_snippet);
2833 expr.span.with_lo(map_args[0].span.hi()),
2834 "called `map(..).flatten()` on an `Option`",
2835 "try using `and_then` instead",
2837 Applicability::MachineApplicable,
2842 const MAP_UNWRAP_OR_MSRV: RustcVersion = RustcVersion::new(1, 41, 0);
2844 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2845 /// Return true if lint triggered
2846 fn lint_map_unwrap_or_else<'tcx>(
2847 cx: &LateContext<'tcx>,
2848 expr: &'tcx hir::Expr<'_>,
2849 map_args: &'tcx [hir::Expr<'_>],
2850 unwrap_args: &'tcx [hir::Expr<'_>],
2851 msrv: Option<&RustcVersion>,
2853 if !meets_msrv(msrv, &MAP_UNWRAP_OR_MSRV) {
2856 // lint if the caller of `map()` is an `Option`
2857 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type);
2858 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::result_type);
2860 if is_option || is_result {
2861 // Don't make a suggestion that may fail to compile due to mutably borrowing
2862 // the same variable twice.
2863 let map_mutated_vars = mutated_variables(&map_args[0], cx);
2864 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2865 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2866 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2874 let msg = if is_option {
2875 "called `map(<f>).unwrap_or_else(<g>)` on an `Option` value. This can be done more directly by calling \
2876 `map_or_else(<g>, <f>)` instead"
2878 "called `map(<f>).unwrap_or_else(<g>)` on a `Result` value. This can be done more directly by calling \
2879 `.map_or_else(<g>, <f>)` instead"
2881 // get snippets for args to map() and unwrap_or_else()
2882 let map_snippet = snippet(cx, map_args[1].span, "..");
2883 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2884 // lint, with note if neither arg is > 1 line and both map() and
2885 // unwrap_or_else() have the same span
2886 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2887 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2888 if same_span && !multiline {
2889 let var_snippet = snippet(cx, map_args[0].span, "..");
2896 format!("{}.map_or_else({}, {})", var_snippet, unwrap_snippet, map_snippet),
2897 Applicability::MachineApplicable,
2900 } else if same_span && multiline {
2901 span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
2909 /// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
2910 fn lint_map_or_none<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>]) {
2911 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym::option_type);
2912 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym::result_type);
2914 // There are two variants of this `map_or` lint:
2915 // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
2916 // (2) using `map_or` as a combinator instead of `and_then`
2918 // (For this lint) we don't care if any other type calls `map_or`
2919 if !is_option && !is_result {
2923 let (lint_name, msg, instead, hint) = {
2924 let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2925 match_qpath(qpath, &paths::OPTION_NONE)
2930 if !default_arg_is_none {
2935 let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
2936 match_qpath(qpath, &paths::OPTION_SOME)
2942 let self_snippet = snippet(cx, map_or_args[0].span, "..");
2943 let func_snippet = snippet(cx, map_or_args[2].span, "..");
2944 let msg = "called `map_or(None, ..)` on an `Option` value. This can be done more directly by calling \
2945 `and_then(..)` instead";
2949 "try using `and_then` instead",
2950 format!("{0}.and_then({1})", self_snippet, func_snippet),
2952 } else if f_arg_is_some {
2953 let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
2955 let self_snippet = snippet(cx, map_or_args[0].span, "..");
2957 RESULT_MAP_OR_INTO_OPTION,
2959 "try using `ok` instead",
2960 format!("{0}.ok()", self_snippet),
2975 Applicability::MachineApplicable,
2979 /// lint use of `filter().next()` for `Iterators`
2980 fn lint_filter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
2981 // lint if caller of `.filter().next()` is an Iterator
2982 if match_trait_method(cx, expr, &paths::ITERATOR) {
2983 let msg = "called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
2984 `.find(..)` instead.";
2985 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2986 if filter_snippet.lines().count() <= 1 {
2987 let iter_snippet = snippet(cx, filter_args[0].span, "..");
2988 // add note if not multi-line
2995 format!("{}.find({})", iter_snippet, filter_snippet),
2996 Applicability::MachineApplicable,
2999 span_lint(cx, FILTER_NEXT, expr.span, msg);
3004 /// lint use of `skip_while().next()` for `Iterators`
3005 fn lint_skip_while_next<'tcx>(
3006 cx: &LateContext<'tcx>,
3007 expr: &'tcx hir::Expr<'_>,
3008 _skip_while_args: &'tcx [hir::Expr<'_>],
3010 // lint if caller of `.skip_while().next()` is an Iterator
3011 if match_trait_method(cx, expr, &paths::ITERATOR) {
3016 "called `skip_while(<p>).next()` on an `Iterator`",
3018 "this is more succinctly expressed by calling `.find(!<p>)` instead",
3023 /// lint use of `filter().map()` or `find().map()` for `Iterators`
3024 fn lint_filter_map<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, is_find: bool) {
3026 if let ExprKind::MethodCall(_, _, [map_recv, map_arg], map_span) = expr.kind;
3027 if let ExprKind::MethodCall(_, _, [_, filter_arg], filter_span) = map_recv.kind;
3028 if match_trait_method(cx, map_recv, &paths::ITERATOR);
3030 // filter(|x| ...is_some())...
3031 if let ExprKind::Closure(_, _, filter_body_id, ..) = filter_arg.kind;
3032 let filter_body = cx.tcx.hir().body(filter_body_id);
3033 if let [filter_param] = filter_body.params;
3034 // optional ref pattern: `filter(|&x| ..)`
3035 let (filter_pat, is_filter_param_ref) = if let PatKind::Ref(ref_pat, _) = filter_param.pat.kind {
3038 (filter_param.pat, false)
3040 // closure ends with is_some() or is_ok()
3041 if let PatKind::Binding(_, filter_param_id, _, None) = filter_pat.kind;
3042 if let ExprKind::MethodCall(path, _, [filter_arg], _) = filter_body.value.kind;
3043 if let Some(opt_ty) = cx.typeck_results().expr_ty(filter_arg).ty_adt_def();
3044 if let Some(is_result) = if cx.tcx.is_diagnostic_item(sym::option_type, opt_ty.did) {
3046 } else if cx.tcx.is_diagnostic_item(sym::result_type, opt_ty.did) {
3051 if path.ident.name.as_str() == if is_result { "is_ok" } else { "is_some" };
3053 // ...map(|x| ...unwrap())
3054 if let ExprKind::Closure(_, _, map_body_id, ..) = map_arg.kind;
3055 let map_body = cx.tcx.hir().body(map_body_id);
3056 if let [map_param] = map_body.params;
3057 if let PatKind::Binding(_, map_param_id, map_param_ident, None) = map_param.pat.kind;
3058 // closure ends with expect() or unwrap()
3059 if let ExprKind::MethodCall(seg, _, [map_arg, ..], _) = map_body.value.kind;
3060 if matches!(seg.ident.name, sym::expect | sym::unwrap | sym::unwrap_or);
3062 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
3063 // in `filter(|x| ..)`, replace `*x` with `x`
3064 let a_path = if_chain! {
3065 if !is_filter_param_ref;
3066 if let ExprKind::Unary(UnOp::UnDeref, expr_path) = a.kind;
3067 then { expr_path } else { a }
3069 // let the filter closure arg and the map closure arg be equal
3071 if let ExprKind::Path(QPath::Resolved(None, a_path)) = a_path.kind;
3072 if let ExprKind::Path(QPath::Resolved(None, b_path)) = b.kind;
3073 if a_path.res == Res::Local(filter_param_id);
3074 if b_path.res == Res::Local(map_param_id);
3075 if TyS::same_type(cx.typeck_results().expr_ty_adjusted(a), cx.typeck_results().expr_ty_adjusted(b));
3082 if SpanlessEq::new(cx).expr_fallback(eq_fallback).eq_expr(filter_arg, map_arg);
3084 let span = filter_span.to(map_span);
3085 let (filter_name, lint) = if is_find {
3086 ("find", MANUAL_FIND_MAP)
3088 ("filter", MANUAL_FILTER_MAP)
3090 let msg = format!("`{}(..).map(..)` can be simplified as `{0}_map(..)`", filter_name);
3091 let to_opt = if is_result { ".ok()" } else { "" };
3092 let sugg = format!("{}_map(|{}| {}{})", filter_name, map_param_ident,
3093 snippet(cx, map_arg.span, ".."), to_opt);
3094 span_lint_and_sugg(cx, lint, span, &msg, "try", sugg, Applicability::MachineApplicable);
3099 const FILTER_MAP_NEXT_MSRV: RustcVersion = RustcVersion::new(1, 30, 0);
3101 /// lint use of `filter_map().next()` for `Iterators`
3102 fn lint_filter_map_next<'tcx>(
3103 cx: &LateContext<'tcx>,
3104 expr: &'tcx hir::Expr<'_>,
3105 filter_args: &'tcx [hir::Expr<'_>],
3106 msrv: Option<&RustcVersion>,
3108 if match_trait_method(cx, expr, &paths::ITERATOR) {
3109 if !meets_msrv(msrv, &FILTER_MAP_NEXT_MSRV) {
3113 let msg = "called `filter_map(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
3114 `.find_map(..)` instead.";
3115 let filter_snippet = snippet(cx, filter_args[1].span, "..");
3116 if filter_snippet.lines().count() <= 1 {
3117 let iter_snippet = snippet(cx, filter_args[0].span, "..");
3124 format!("{}.find_map({})", iter_snippet, filter_snippet),
3125 Applicability::MachineApplicable,
3128 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
3133 /// lint use of `filter_map().map()` for `Iterators`
3134 fn lint_filter_map_map<'tcx>(
3135 cx: &LateContext<'tcx>,
3136 expr: &'tcx hir::Expr<'_>,
3137 _filter_args: &'tcx [hir::Expr<'_>],
3138 _map_args: &'tcx [hir::Expr<'_>],
3140 // lint if caller of `.filter_map().map()` is an Iterator
3141 if match_trait_method(cx, expr, &paths::ITERATOR) {
3142 let msg = "called `filter_map(..).map(..)` on an `Iterator`";
3143 let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
3144 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3148 /// lint use of `filter().flat_map()` for `Iterators`
3149 fn lint_filter_flat_map<'tcx>(
3150 cx: &LateContext<'tcx>,
3151 expr: &'tcx hir::Expr<'_>,
3152 _filter_args: &'tcx [hir::Expr<'_>],
3153 _map_args: &'tcx [hir::Expr<'_>],
3155 // lint if caller of `.filter().flat_map()` is an Iterator
3156 if match_trait_method(cx, expr, &paths::ITERATOR) {
3157 let msg = "called `filter(..).flat_map(..)` on an `Iterator`";
3158 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
3159 and filtering by returning `iter::empty()`";
3160 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3164 /// lint use of `filter_map().flat_map()` for `Iterators`
3165 fn lint_filter_map_flat_map<'tcx>(
3166 cx: &LateContext<'tcx>,
3167 expr: &'tcx hir::Expr<'_>,
3168 _filter_args: &'tcx [hir::Expr<'_>],
3169 _map_args: &'tcx [hir::Expr<'_>],
3171 // lint if caller of `.filter_map().flat_map()` is an Iterator
3172 if match_trait_method(cx, expr, &paths::ITERATOR) {
3173 let msg = "called `filter_map(..).flat_map(..)` on an `Iterator`";
3174 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
3175 and filtering by returning `iter::empty()`";
3176 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3180 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
3181 fn lint_flat_map_identity<'tcx>(
3182 cx: &LateContext<'tcx>,
3183 expr: &'tcx hir::Expr<'_>,
3184 flat_map_args: &'tcx [hir::Expr<'_>],
3185 flat_map_span: Span,
3187 if match_trait_method(cx, expr, &paths::ITERATOR) {
3188 let arg_node = &flat_map_args[1].kind;
3190 let apply_lint = |message: &str| {
3194 flat_map_span.with_hi(expr.span.hi()),
3197 "flatten()".to_string(),
3198 Applicability::MachineApplicable,
3203 if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
3204 let body = cx.tcx.hir().body(*body_id);
3206 if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
3207 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
3209 if path.segments.len() == 1;
3210 if path.segments[0].ident.name == binding_ident.name;
3213 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
3218 if let hir::ExprKind::Path(ref qpath) = arg_node;
3220 if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
3223 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
3229 /// lint searching an Iterator followed by `is_some()`
3230 /// or calling `find()` on a string followed by `is_some()`
3231 fn lint_search_is_some<'tcx>(
3232 cx: &LateContext<'tcx>,
3233 expr: &'tcx hir::Expr<'_>,
3234 search_method: &str,
3235 search_args: &'tcx [hir::Expr<'_>],
3236 is_some_args: &'tcx [hir::Expr<'_>],
3239 // lint if caller of search is an Iterator
3240 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
3242 "called `is_some()` after searching an `Iterator` with `{}`",
3245 let hint = "this is more succinctly expressed by calling `any()`";
3246 let search_snippet = snippet(cx, search_args[1].span, "..");
3247 if search_snippet.lines().count() <= 1 {
3248 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
3249 // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
3250 let any_search_snippet = if_chain! {
3251 if search_method == "find";
3252 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
3253 let closure_body = cx.tcx.hir().body(body_id);
3254 if let Some(closure_arg) = closure_body.params.get(0);
3256 if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
3257 Some(search_snippet.replacen('&', "", 1))
3258 } else if let Some(name) = get_arg_name(&closure_arg.pat) {
3259 Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
3267 // add note if not multi-line
3271 method_span.with_hi(expr.span.hi()),
3273 "use `any()` instead",
3276 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
3278 Applicability::MachineApplicable,
3281 span_lint_and_help(cx, SEARCH_IS_SOME, expr.span, &msg, None, hint);
3284 // lint if `find()` is called by `String` or `&str`
3285 else if search_method == "find" {
3286 let is_string_or_str_slice = |e| {
3287 let self_ty = cx.typeck_results().expr_ty(e).peel_refs();
3288 if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
3291 *self_ty.kind() == ty::Str
3295 if is_string_or_str_slice(&search_args[0]);
3296 if is_string_or_str_slice(&search_args[1]);
3298 let msg = "called `is_some()` after calling `find()` on a string";
3299 let mut applicability = Applicability::MachineApplicable;
3300 let find_arg = snippet_with_applicability(cx, search_args[1].span, "..", &mut applicability);
3304 method_span.with_hi(expr.span.hi()),
3306 "use `contains()` instead",
3307 format!("contains({})", find_arg),
3315 /// Used for `lint_binary_expr_with_method_call`.
3316 #[derive(Copy, Clone)]
3317 struct BinaryExprInfo<'a> {
3318 expr: &'a hir::Expr<'a>,
3319 chain: &'a hir::Expr<'a>,
3320 other: &'a hir::Expr<'a>,
3324 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3325 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3326 macro_rules! lint_with_both_lhs_and_rhs {
3327 ($func:ident, $cx:expr, $info:ident) => {
3328 if !$func($cx, $info) {
3329 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3330 if $func($cx, $info) {
3337 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
3338 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
3339 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
3340 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
3343 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3345 cx: &LateContext<'_>,
3346 info: &BinaryExprInfo<'_>,
3347 chain_methods: &[&str],
3348 lint: &'static Lint,
3352 if let Some(args) = method_chain_args(info.chain, chain_methods);
3353 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
3354 if arg_char.len() == 1;
3355 if let hir::ExprKind::Path(ref qpath) = fun.kind;
3356 if let Some(segment) = single_segment_path(qpath);
3357 if segment.ident.name == sym::Some;
3359 let mut applicability = Applicability::MachineApplicable;
3360 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
3362 if *self_ty.kind() != ty::Str {
3370 &format!("you should use the `{}` method", suggest),
3372 format!("{}{}.{}({})",
3373 if info.eq { "" } else { "!" },
3374 snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3376 snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
3387 /// Checks for the `CHARS_NEXT_CMP` lint.
3388 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3389 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
3392 /// Checks for the `CHARS_LAST_CMP` lint.
3393 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3394 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
3397 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
3401 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
3402 fn lint_chars_cmp_with_unwrap<'tcx>(
3403 cx: &LateContext<'tcx>,
3404 info: &BinaryExprInfo<'_>,
3405 chain_methods: &[&str],
3406 lint: &'static Lint,
3410 if let Some(args) = method_chain_args(info.chain, chain_methods);
3411 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
3412 if let ast::LitKind::Char(c) = lit.node;
3414 let mut applicability = Applicability::MachineApplicable;
3419 &format!("you should use the `{}` method", suggest),
3421 format!("{}{}.{}('{}')",
3422 if info.eq { "" } else { "!" },
3423 snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3436 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
3437 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3438 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3441 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3442 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3443 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3446 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3450 fn get_hint_if_single_char_arg(
3451 cx: &LateContext<'_>,
3452 arg: &hir::Expr<'_>,
3453 applicability: &mut Applicability,
3454 ) -> Option<String> {
3456 if let hir::ExprKind::Lit(lit) = &arg.kind;
3457 if let ast::LitKind::Str(r, style) = lit.node;
3458 let string = r.as_str();
3459 if string.chars().count() == 1;
3461 let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
3462 let ch = if let ast::StrStyle::Raw(nhash) = style {
3463 let nhash = nhash as usize;
3464 // for raw string: r##"a"##
3465 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3467 // for regular string: "a"
3468 &snip[1..(snip.len() - 1)]
3470 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3478 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3479 fn lint_single_char_pattern(cx: &LateContext<'_>, _expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
3480 let mut applicability = Applicability::MachineApplicable;
3481 if let Some(hint) = get_hint_if_single_char_arg(cx, arg, &mut applicability) {
3484 SINGLE_CHAR_PATTERN,
3486 "single-character string constant used as pattern",
3487 "try using a `char` instead",
3494 /// lint for length-1 `str`s as argument for `push_str`
3495 fn lint_single_char_push_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3496 let mut applicability = Applicability::MachineApplicable;
3497 if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[1], &mut applicability) {
3498 let base_string_snippet =
3499 snippet_with_applicability(cx, args[0].span.source_callsite(), "..", &mut applicability);
3500 let sugg = format!("{}.push({})", base_string_snippet, extension_string);
3503 SINGLE_CHAR_ADD_STR,
3505 "calling `push_str()` using a single-character string literal",
3506 "consider using `push` with a character literal",
3513 /// lint for length-1 `str`s as argument for `insert_str`
3514 fn lint_single_char_insert_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3515 let mut applicability = Applicability::MachineApplicable;
3516 if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[2], &mut applicability) {
3517 let base_string_snippet =
3518 snippet_with_applicability(cx, args[0].span.source_callsite(), "_", &mut applicability);
3519 let pos_arg = snippet_with_applicability(cx, args[1].span, "..", &mut applicability);
3520 let sugg = format!("{}.insert({}, {})", base_string_snippet, pos_arg, extension_string);
3523 SINGLE_CHAR_ADD_STR,
3525 "calling `insert_str()` using a single-character string literal",
3526 "consider using `insert` with a character literal",
3533 /// Checks for the `USELESS_ASREF` lint.
3534 fn lint_asref(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3535 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3536 // check if the call is to the actual `AsRef` or `AsMut` trait
3537 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3538 // check if the type after `as_ref` or `as_mut` is the same as before
3539 let recvr = &as_ref_args[0];
3540 let rcv_ty = cx.typeck_results().expr_ty(recvr);
3541 let res_ty = cx.typeck_results().expr_ty(expr);
3542 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3543 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3544 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3545 // allow the `as_ref` or `as_mut` if it is followed by another method call
3547 if let Some(parent) = get_parent_expr(cx, expr);
3548 if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind;
3549 if span != &expr.span;
3555 let mut applicability = Applicability::MachineApplicable;
3560 &format!("this call to `{}` does nothing", call_name),
3562 snippet_with_applicability(cx, recvr.span, "..", &mut applicability).to_string(),
3569 fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3570 has_iter_method(cx, self_ref_ty).map(|ty_name| {
3571 let mutbl = match self_ref_ty.kind() {
3572 ty::Ref(_, _, mutbl) => mutbl,
3573 _ => unreachable!(),
3575 let method_name = match mutbl {
3576 hir::Mutability::Not => "iter",
3577 hir::Mutability::Mut => "iter_mut",
3579 (ty_name, method_name)
3583 fn lint_into_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3584 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3587 if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3593 "this `.into_iter()` call is equivalent to `.{}()` and will not consume the `{}`",
3597 method_name.to_string(),
3598 Applicability::MachineApplicable,
3603 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3604 fn lint_maybe_uninit(cx: &LateContext<'_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3606 if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3608 if let hir::ExprKind::Path(ref path) = callee.kind;
3609 if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3610 if !is_maybe_uninit_ty_valid(cx, cx.typeck_results().expr_ty_adjusted(outer));
3614 UNINIT_ASSUMED_INIT,
3616 "this call for this type may be undefined behavior"
3622 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
3624 ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3625 ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3626 ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
3631 fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
3636 "this call to `map()` won't have an effect on the call to `count()`",
3638 "make sure you did not confuse `map` with `filter` or `for_each`",
3642 const OPTION_AS_REF_DEREF_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
3644 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3645 fn lint_option_as_ref_deref<'tcx>(
3646 cx: &LateContext<'tcx>,
3647 expr: &hir::Expr<'_>,
3648 as_ref_args: &[hir::Expr<'_>],
3649 map_args: &[hir::Expr<'_>],
3651 msrv: Option<&RustcVersion>,
3653 if !meets_msrv(msrv, &OPTION_AS_REF_DEREF_MSRV) {
3657 let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
3659 let option_ty = cx.typeck_results().expr_ty(&as_ref_args[0]);
3660 if !is_type_diagnostic_item(cx, option_ty, sym::option_type) {
3664 let deref_aliases: [&[&str]; 9] = [
3665 &paths::DEREF_TRAIT_METHOD,
3666 &paths::DEREF_MUT_TRAIT_METHOD,
3667 &paths::CSTRING_AS_C_STR,
3668 &paths::OS_STRING_AS_OS_STR,
3669 &paths::PATH_BUF_AS_PATH,
3670 &paths::STRING_AS_STR,
3671 &paths::STRING_AS_MUT_STR,
3672 &paths::VEC_AS_SLICE,
3673 &paths::VEC_AS_MUT_SLICE,
3676 let is_deref = match map_args[1].kind {
3677 hir::ExprKind::Path(ref expr_qpath) => cx
3678 .qpath_res(expr_qpath, map_args[1].hir_id)
3680 .map_or(false, |fun_def_id| {
3681 deref_aliases.iter().any(|path| match_def_path(cx, fun_def_id, path))
3683 hir::ExprKind::Closure(_, _, body_id, _, _) => {
3684 let closure_body = cx.tcx.hir().body(body_id);
3685 let closure_expr = remove_blocks(&closure_body.value);
3687 match &closure_expr.kind {
3688 hir::ExprKind::MethodCall(_, _, args, _) => {
3691 if let hir::ExprKind::Path(qpath) = &args[0].kind;
3692 if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, args[0].hir_id);
3693 if closure_body.params[0].pat.hir_id == local_id;
3696 .expr_adjustments(&args[0])
3699 .collect::<Box<[_]>>();
3700 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3702 let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
3703 deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3709 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
3711 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind;
3712 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind;
3713 if let hir::ExprKind::Path(ref qpath) = inner2.kind;
3714 if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, inner2.hir_id);
3716 closure_body.params[0].pat.hir_id == local_id
3729 let current_method = if is_mut {
3730 format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
3732 format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
3734 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3735 let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3736 let suggestion = format!("try using {} instead", method_hint);
3739 "called `{0}` on an Option value. This can be done more directly \
3740 by calling `{1}` instead",
3741 current_method, hint
3745 OPTION_AS_REF_DEREF,
3750 Applicability::MachineApplicable,
3755 fn lint_map_collect(
3756 cx: &LateContext<'_>,
3757 expr: &hir::Expr<'_>,
3758 map_args: &[hir::Expr<'_>],
3759 collect_args: &[hir::Expr<'_>],
3762 // called on Iterator
3763 if let [map_expr] = collect_args;
3764 if match_trait_method(cx, map_expr, &paths::ITERATOR);
3765 // return of collect `Result<(),_>`
3766 let collect_ret_ty = cx.typeck_results().expr_ty(expr);
3767 if is_type_diagnostic_item(cx, collect_ret_ty, sym::result_type);
3768 if let ty::Adt(_, substs) = collect_ret_ty.kind();
3769 if let Some(result_t) = substs.types().next();
3770 if result_t.is_unit();
3771 // get parts for snippet
3772 if let [iter, map_fn] = map_args;
3776 MAP_COLLECT_RESULT_UNIT,
3778 "`.map().collect()` can be replaced with `.try_for_each()`",
3781 "{}.try_for_each({})",
3782 snippet(cx, iter.span, ".."),
3783 snippet(cx, map_fn.span, "..")
3785 Applicability::MachineApplicable,
3791 /// Given a `Result<T, E>` type, return its error type (`E`).
3792 fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3794 ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym::result_type) => substs.types().nth(1),
3799 /// This checks whether a given type is known to implement Debug.
3800 fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
3802 .get_diagnostic_item(sym::debug_trait)
3803 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3808 StartsWith(&'static str),
3812 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3813 (Convention::Eq("new"), &[SelfKind::No]),
3814 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3815 (Convention::StartsWith("from_"), &[SelfKind::No]),
3816 (Convention::StartsWith("into_"), &[SelfKind::Value]),
3817 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3818 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3819 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3822 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3823 unsafety: hir::Unsafety::Normal,
3824 constness: hir::Constness::NotConst,
3825 asyncness: hir::IsAsync::NotAsync,
3826 abi: rustc_target::spec::abi::Abi::Rust,
3829 struct ShouldImplTraitCase {
3830 trait_name: &'static str,
3831 method_name: &'static str,
3833 fn_header: hir::FnHeader,
3834 // implicit self kind expected (none, self, &self, ...)
3835 self_kind: SelfKind,
3836 // checks against the output type
3837 output_type: OutType,
3838 // certain methods with explicit lifetimes can't implement the equivalent trait method
3839 lint_explicit_lifetime: bool,
3841 impl ShouldImplTraitCase {
3843 trait_name: &'static str,
3844 method_name: &'static str,
3846 fn_header: hir::FnHeader,
3847 self_kind: SelfKind,
3848 output_type: OutType,
3849 lint_explicit_lifetime: bool,
3850 ) -> ShouldImplTraitCase {
3851 ShouldImplTraitCase {
3858 lint_explicit_lifetime,
3862 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3863 self.lint_explicit_lifetime
3864 || !impl_item.generics.params.iter().any(|p| {
3867 hir::GenericParamKind::Lifetime {
3868 kind: hir::LifetimeParamKind::Explicit
3876 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
3877 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3878 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3879 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3880 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3881 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3882 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3883 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3884 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3885 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3886 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
3887 // FIXME: default doesn't work
3888 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
3889 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3890 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3891 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3892 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
3893 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
3894 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3895 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
3896 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
3897 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
3898 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
3899 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3900 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3901 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3902 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
3903 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
3904 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3905 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3906 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3907 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
3911 const PATTERN_METHODS: [(&str, usize); 17] = [
3919 ("split_terminator", 1),
3920 ("rsplit_terminator", 1),
3925 ("match_indices", 1),
3926 ("rmatch_indices", 1),
3927 ("trim_start_matches", 1),
3928 ("trim_end_matches", 1),
3931 #[derive(Clone, Copy, PartialEq, Debug)]
3940 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3941 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3942 if ty == parent_ty {
3944 } else if ty.is_box() {
3945 ty.boxed_ty() == parent_ty
3946 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3947 if let ty::Adt(_, substs) = ty.kind() {
3948 substs.types().next().map_or(false, |t| t == parent_ty)
3957 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3958 if let ty::Ref(_, t, m) = *ty.kind() {
3959 return m == mutability && t == parent_ty;
3962 let trait_path = match mutability {
3963 hir::Mutability::Not => &paths::ASREF_TRAIT,
3964 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3967 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3969 None => return false,
3971 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3975 Self::Value => matches_value(cx, parent_ty, ty),
3976 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3977 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3978 Self::No => ty != parent_ty,
3983 fn description(self) -> &'static str {
3985 Self::Value => "self by value",
3986 Self::Ref => "self by reference",
3987 Self::RefMut => "self by mutable reference",
3988 Self::No => "no self",
3995 fn check(&self, other: &str) -> bool {
3997 Self::Eq(this) => this == other,
3998 Self::StartsWith(this) => other.starts_with(this) && this != other,
4003 impl fmt::Display for Convention {
4004 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
4006 Self::Eq(this) => this.fmt(f),
4007 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
4012 #[derive(Clone, Copy)]
4021 fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
4022 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
4024 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
4025 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
4026 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
4027 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
4028 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
4034 fn is_bool(ty: &hir::Ty<'_>) -> bool {
4035 if let hir::TyKind::Path(ref p) = ty.kind {
4036 match_qpath(p, &["bool"])
4042 fn check_pointer_offset(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4045 if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.typeck_results().expr_ty(&args[0]).kind();
4046 if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
4049 span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
4054 fn lint_filetype_is_file(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4055 let ty = cx.typeck_results().expr_ty(&args[0]);
4057 if !match_type(cx, ty, &paths::FILE_TYPE) {
4063 let lint_unary: &str;
4064 let help_unary: &str;
4066 if let Some(parent) = get_parent_expr(cx, expr);
4067 if let hir::ExprKind::Unary(op, _) = parent.kind;
4068 if op == hir::UnOp::UnNot;
4081 let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
4082 let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
4083 span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
4086 fn lint_from_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4087 let ty = cx.typeck_results().expr_ty(expr);
4088 let arg_ty = cx.typeck_results().expr_ty(&args[0]);
4091 if let Some(from_iter_id) = get_trait_def_id(cx, &paths::FROM_ITERATOR);
4092 if let Some(iter_id) = get_trait_def_id(cx, &paths::ITERATOR);
4094 if implements_trait(cx, ty, from_iter_id, &[]) && implements_trait(cx, arg_ty, iter_id, &[]);
4096 // `expr` implements `FromIterator` trait
4097 let iter_expr = snippet(cx, args[0].span, "..");
4100 FROM_ITER_INSTEAD_OF_COLLECT,
4102 "usage of `FromIterator::from_iter`",
4103 "use `.collect()` instead of `::from_iter()`",
4104 format!("{}.collect()", iter_expr),
4105 Applicability::MaybeIncorrect,
4111 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
4112 expected.constness == actual.constness
4113 && expected.unsafety == actual.unsafety
4114 && expected.asyncness == actual.asyncness