1 mod bind_instead_of_map;
3 mod filter_map_identity;
5 mod inefficient_to_string;
8 mod manual_saturating_arithmetic;
9 mod option_map_unwrap_or;
10 mod unnecessary_filter_map;
11 mod unnecessary_lazy_eval;
17 use bind_instead_of_map::BindInsteadOfMap;
18 use if_chain::if_chain;
20 use rustc_errors::Applicability;
22 use rustc_hir::{Expr, ExprKind, PatKind, TraitItem, TraitItemKind, UnOp};
23 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
24 use rustc_middle::lint::in_external_macro;
25 use rustc_middle::ty::{self, TraitRef, Ty, TyS};
26 use rustc_semver::RustcVersion;
27 use rustc_session::{declare_tool_lint, impl_lint_pass};
28 use rustc_span::source_map::Span;
29 use rustc_span::symbol::{sym, SymbolStr};
30 use rustc_typeck::hir_ty_to_ty;
32 use crate::consts::{constant, Constant};
33 use crate::utils::eager_or_lazy::is_lazyness_candidate;
34 use crate::utils::usage::mutated_variables;
36 contains_return, contains_ty, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
37 in_macro, is_copy, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment, match_def_path,
38 match_qpath, match_trait_method, match_type, meets_msrv, method_calls, method_chain_args, path_to_local_id, paths,
39 remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite,
40 span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, strip_pat_refs, sugg, walk_ptrs_ty_depth,
44 declare_clippy_lint! {
45 /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
47 /// **Why is this bad?** It is better to handle the `None` or `Err` case,
48 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
49 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
50 /// `Allow` by default.
52 /// `result.unwrap()` will let the thread panic on `Err` values.
53 /// Normally, you want to implement more sophisticated error handling,
54 /// and propagate errors upwards with `?` operator.
56 /// Even if you want to panic on errors, not all `Error`s implement good
57 /// messages on display. Therefore, it may be beneficial to look at the places
58 /// where they may get displayed. Activate this lint to do just that.
60 /// **Known problems:** None.
64 /// # let opt = Some(1);
70 /// opt.expect("more helpful message");
76 /// # let res: Result<usize, ()> = Ok(1);
82 /// res.expect("more helpful message");
86 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
89 declare_clippy_lint! {
90 /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
92 /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
93 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
94 /// this lint is `Allow` by default.
96 /// `result.expect()` will let the thread panic on `Err`
97 /// values. Normally, you want to implement more sophisticated error handling,
98 /// and propagate errors upwards with `?` operator.
100 /// **Known problems:** None.
104 /// # let opt = Some(1);
107 /// opt.expect("one");
110 /// let opt = Some(1);
117 /// # let res: Result<usize, ()> = Ok(1);
120 /// res.expect("one");
124 /// # Ok::<(), ()>(())
128 "using `.expect()` on `Result` or `Option`, which might be better handled"
131 declare_clippy_lint! {
132 /// **What it does:** Checks for methods that should live in a trait
133 /// implementation of a `std` trait (see [llogiq's blog
134 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
135 /// information) instead of an inherent implementation.
137 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
138 /// the code, often with very little cost. Also people seeing a `mul(...)`
140 /// may expect `*` to work equally, so you should have good reason to disappoint
143 /// **Known problems:** None.
149 /// fn add(&self, other: &X) -> X {
155 pub SHOULD_IMPLEMENT_TRAIT,
157 "defining a method that should be implementing a std trait"
160 declare_clippy_lint! {
161 /// **What it does:** Checks for methods with certain name prefixes and which
162 /// doesn't match how self is taken. The actual rules are:
164 /// |Prefix |`self` taken |
165 /// |-------|----------------------|
166 /// |`as_` |`&self` or `&mut self`|
168 /// |`into_`|`self` |
169 /// |`is_` |`&self` or none |
170 /// |`to_` |`&self` |
172 /// **Why is this bad?** Consistency breeds readability. If you follow the
173 /// conventions, your users won't be surprised that they, e.g., need to supply a
174 /// mutable reference to a `as_..` function.
176 /// **Known problems:** None.
182 /// fn as_str(self) -> &'static str {
188 pub WRONG_SELF_CONVENTION,
190 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
193 declare_clippy_lint! {
194 /// **What it does:** This is the same as
195 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
197 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
199 /// **Known problems:** Actually *renaming* the function may break clients if
200 /// the function is part of the public interface. In that case, be mindful of
201 /// the stability guarantees you've given your users.
207 /// pub fn as_str(self) -> &'a str {
212 pub WRONG_PUB_SELF_CONVENTION,
214 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
217 declare_clippy_lint! {
218 /// **What it does:** Checks for usage of `ok().expect(..)`.
220 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
221 /// directly to get a better error message.
223 /// **Known problems:** The error type needs to implement `Debug`
227 /// # let x = Ok::<_, ()>(());
230 /// x.ok().expect("why did I do this again?");
233 /// x.expect("why did I do this again?");
237 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
240 declare_clippy_lint! {
241 /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
242 /// `result.map(_).unwrap_or_else(_)`.
244 /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
245 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
247 /// **Known problems:** The order of the arguments is not in execution order
251 /// # let x = Some(1);
254 /// x.map(|a| a + 1).unwrap_or(0);
257 /// x.map_or(0, |a| a + 1);
263 /// # let x: Result<usize, ()> = Ok(1);
264 /// # fn some_function(foo: ()) -> usize { 1 }
267 /// x.map(|a| a + 1).unwrap_or_else(some_function);
270 /// x.map_or_else(some_function, |a| a + 1);
274 "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)`"
277 declare_clippy_lint! {
278 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
280 /// **Why is this bad?** Readability, this can be written more concisely as
283 /// **Known problems:** The order of the arguments is not in execution order.
287 /// # let opt = Some(1);
290 /// opt.map_or(None, |a| Some(a + 1));
293 /// opt.and_then(|a| Some(a + 1));
295 pub OPTION_MAP_OR_NONE,
297 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
300 declare_clippy_lint! {
301 /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
303 /// **Why is this bad?** Readability, this can be written more concisely as
306 /// **Known problems:** None.
312 /// # let r: Result<u32, &str> = Ok(1);
313 /// assert_eq!(Some(1), r.map_or(None, Some));
318 /// # let r: Result<u32, &str> = Ok(1);
319 /// assert_eq!(Some(1), r.ok());
321 pub RESULT_MAP_OR_INTO_OPTION,
323 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
326 declare_clippy_lint! {
327 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
328 /// `_.or_else(|x| Err(y))`.
330 /// **Why is this bad?** Readability, this can be written more concisely as
331 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
333 /// **Known problems:** None
338 /// # fn opt() -> Option<&'static str> { Some("42") }
339 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
340 /// let _ = opt().and_then(|s| Some(s.len()));
341 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
342 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
345 /// The correct use would be:
348 /// # fn opt() -> Option<&'static str> { Some("42") }
349 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
350 /// let _ = opt().map(|s| s.len());
351 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
352 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
354 pub BIND_INSTEAD_OF_MAP,
356 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
359 declare_clippy_lint! {
360 /// **What it does:** Checks for usage of `_.filter(_).next()`.
362 /// **Why is this bad?** Readability, this can be written more concisely as
365 /// **Known problems:** None.
369 /// # let vec = vec![1];
370 /// vec.iter().filter(|x| **x == 0).next();
372 /// Could be written as
374 /// # let vec = vec![1];
375 /// vec.iter().find(|x| **x == 0);
379 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
382 declare_clippy_lint! {
383 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
385 /// **Why is this bad?** Readability, this can be written more concisely as
386 /// `_.find(!condition)`.
388 /// **Known problems:** None.
392 /// # let vec = vec![1];
393 /// vec.iter().skip_while(|x| **x == 0).next();
395 /// Could be written as
397 /// # let vec = vec![1];
398 /// vec.iter().find(|x| **x != 0);
402 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
405 declare_clippy_lint! {
406 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
408 /// **Why is this bad?** Readability, this can be written more concisely as
411 /// **Known problems:**
415 /// let vec = vec![vec![1]];
418 /// vec.iter().map(|x| x.iter()).flatten();
421 /// vec.iter().flat_map(|x| x.iter());
425 "using combinations of `flatten` and `map` which can usually be written as a single method call"
428 declare_clippy_lint! {
429 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
430 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
432 /// **Why is this bad?** Readability, this can be written more concisely as
433 /// `_.filter_map(_)`.
435 /// **Known problems:** Often requires a condition + Option/Iterator creation
436 /// inside the closure.
440 /// let vec = vec![1];
443 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
446 /// vec.iter().filter_map(|x| if *x == 0 {
454 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
457 declare_clippy_lint! {
458 /// **What it does:** Checks for usage of `_.filter(_).map(_)` that can be written more simply
459 /// as `filter_map(_)`.
461 /// **Why is this bad?** Redundant code in the `filter` and `map` operations is poor style and
464 /// **Known problems:** None.
470 /// .filter(|n| n.checked_add(1).is_some())
471 /// .map(|n| n.checked_add(1).unwrap());
476 /// (0_i32..10).filter_map(|n| n.checked_add(1));
478 pub MANUAL_FILTER_MAP,
480 "using `_.filter(_).map(_)` in a way that can be written more simply as `filter_map(_)`"
483 declare_clippy_lint! {
484 /// **What it does:** Checks for usage of `_.find(_).map(_)` that can be written more simply
485 /// as `find_map(_)`.
487 /// **Why is this bad?** Redundant code in the `find` and `map` operations is poor style and
490 /// **Known problems:** None.
496 /// .find(|n| n.checked_add(1).is_some())
497 /// .map(|n| n.checked_add(1).unwrap());
502 /// (0_i32..10).find_map(|n| n.checked_add(1));
506 "using `_.find(_).map(_)` in a way that can be written more simply as `find_map(_)`"
509 declare_clippy_lint! {
510 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
512 /// **Why is this bad?** Readability, this can be written more concisely as
515 /// **Known problems:** None
519 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
521 /// Can be written as
524 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
528 "using combination of `filter_map` and `next` which can usually be written as a single method call"
531 declare_clippy_lint! {
532 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
534 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
536 /// **Known problems:** None
540 /// # let iter = vec![vec![0]].into_iter();
541 /// iter.flat_map(|x| x);
543 /// Can be written as
545 /// # let iter = vec![vec![0]].into_iter();
548 pub FLAT_MAP_IDENTITY,
550 "call to `flat_map` where `flatten` is sufficient"
553 declare_clippy_lint! {
554 /// **What it does:** Checks for an iterator or string search (such as `find()`,
555 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
557 /// **Why is this bad?** Readability, this can be written more concisely as
558 /// `_.any(_)` or `_.contains(_)`.
560 /// **Known problems:** None.
564 /// # let vec = vec![1];
565 /// vec.iter().find(|x| **x == 0).is_some();
567 /// Could be written as
569 /// # let vec = vec![1];
570 /// vec.iter().any(|x| *x == 0);
574 "using an iterator or string search followed by `is_some()`, which is more succinctly expressed as a call to `any()` or `contains()`"
577 declare_clippy_lint! {
578 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
579 /// if it starts with a given char.
581 /// **Why is this bad?** Readability, this can be written more concisely as
582 /// `_.starts_with(_)`.
584 /// **Known problems:** None.
588 /// let name = "foo";
589 /// if name.chars().next() == Some('_') {};
591 /// Could be written as
593 /// let name = "foo";
594 /// if name.starts_with('_') {};
598 "using `.chars().next()` to check if a string starts with a char"
601 declare_clippy_lint! {
602 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
603 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
604 /// `unwrap_or_default` instead.
606 /// **Why is this bad?** The function will always be called and potentially
607 /// allocate an object acting as the default.
609 /// **Known problems:** If the function has side-effects, not calling it will
610 /// change the semantic of the program, but you shouldn't rely on that anyway.
614 /// # let foo = Some(String::new());
615 /// foo.unwrap_or(String::new());
617 /// this can instead be written:
619 /// # let foo = Some(String::new());
620 /// foo.unwrap_or_else(String::new);
624 /// # let foo = Some(String::new());
625 /// foo.unwrap_or_default();
629 "using any `*or` method with a function call, which suggests `*or_else`"
632 declare_clippy_lint! {
633 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
634 /// etc., and suggests to use `unwrap_or_else` instead
636 /// **Why is this bad?** The function will always be called.
638 /// **Known problems:** If the function has side-effects, not calling it will
639 /// change the semantics of the program, but you shouldn't rely on that anyway.
643 /// # let foo = Some(String::new());
644 /// # let err_code = "418";
645 /// # let err_msg = "I'm a teapot";
646 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
650 /// # let foo = Some(String::new());
651 /// # let err_code = "418";
652 /// # let err_msg = "I'm a teapot";
653 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
655 /// this can instead be written:
657 /// # let foo = Some(String::new());
658 /// # let err_code = "418";
659 /// # let err_msg = "I'm a teapot";
660 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
664 "using any `expect` method with a function call"
667 declare_clippy_lint! {
668 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
670 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
671 /// generics, not for using the `clone` method on a concrete type.
673 /// **Known problems:** None.
681 "using `clone` on a `Copy` type"
684 declare_clippy_lint! {
685 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
686 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
687 /// function syntax instead (e.g., `Rc::clone(foo)`).
689 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
690 /// can obscure the fact that only the pointer is being cloned, not the underlying
695 /// # use std::rc::Rc;
696 /// let x = Rc::new(1);
704 pub CLONE_ON_REF_PTR,
706 "using 'clone' on a ref-counted pointer"
709 declare_clippy_lint! {
710 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
712 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
713 /// cloning the underlying `T`.
715 /// **Known problems:** None.
722 /// let z = y.clone();
723 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
726 pub CLONE_DOUBLE_REF,
728 "using `clone` on `&&T`"
731 declare_clippy_lint! {
732 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
733 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
735 /// **Why is this bad?** This bypasses the specialized implementation of
736 /// `ToString` and instead goes through the more expensive string formatting
739 /// **Known problems:** None.
743 /// // Generic implementation for `T: Display` is used (slow)
744 /// ["foo", "bar"].iter().map(|s| s.to_string());
746 /// // OK, the specialized impl is used
747 /// ["foo", "bar"].iter().map(|&s| s.to_string());
749 pub INEFFICIENT_TO_STRING,
751 "using `to_string` on `&&T` where `T: ToString`"
754 declare_clippy_lint! {
755 /// **What it does:** Checks for `new` not returning a type that contains `Self`.
757 /// **Why is this bad?** As a convention, `new` methods are used to make a new
758 /// instance of a type.
760 /// **Known problems:** None.
763 /// In an impl block:
766 /// # struct NotAFoo;
768 /// fn new() -> NotAFoo {
778 /// // Bad. The type name must contain `Self`
779 /// fn new() -> Bar {
787 /// # struct FooError;
789 /// // Good. Return type contains `Self`
790 /// fn new() -> Result<Foo, FooError> {
796 /// Or in a trait definition:
798 /// pub trait Trait {
799 /// // Bad. The type name must contain `Self`
805 /// pub trait Trait {
806 /// // Good. Return type contains `Self`
807 /// fn new() -> Self;
812 "not returning type containing `Self` in a `new` method"
815 declare_clippy_lint! {
816 /// **What it does:** Checks for string methods that receive a single-character
817 /// `str` as an argument, e.g., `_.split("x")`.
819 /// **Why is this bad?** Performing these methods using a `char` is faster than
822 /// **Known problems:** Does not catch multi-byte unicode characters.
831 pub SINGLE_CHAR_PATTERN,
833 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
836 declare_clippy_lint! {
837 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
839 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
840 /// actually intend to panic.
842 /// **Known problems:** None.
845 /// ```rust,should_panic
846 /// for x in (0..100).step_by(0) {
850 pub ITERATOR_STEP_BY_ZERO,
852 "using `Iterator::step_by(0)`, which will panic at runtime"
855 declare_clippy_lint! {
856 /// **What it does:** Checks for the use of `iter.nth(0)`.
858 /// **Why is this bad?** `iter.next()` is equivalent to
859 /// `iter.nth(0)`, as they both consume the next element,
860 /// but is more readable.
862 /// **Known problems:** None.
867 /// # use std::collections::HashSet;
869 /// # let mut s = HashSet::new();
871 /// let x = s.iter().nth(0);
874 /// # let mut s = HashSet::new();
876 /// let x = s.iter().next();
880 "replace `iter.nth(0)` with `iter.next()`"
883 declare_clippy_lint! {
884 /// **What it does:** Checks for use of `.iter().nth()` (and the related
885 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
887 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
890 /// **Known problems:** None.
894 /// let some_vec = vec![0, 1, 2, 3];
895 /// let bad_vec = some_vec.iter().nth(3);
896 /// let bad_slice = &some_vec[..].iter().nth(3);
898 /// The correct use would be:
900 /// let some_vec = vec![0, 1, 2, 3];
901 /// let bad_vec = some_vec.get(3);
902 /// let bad_slice = &some_vec[..].get(3);
906 "using `.iter().nth()` on a standard library type with O(1) element access"
909 declare_clippy_lint! {
910 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
912 /// **Why is this bad?** `.nth(x)` is cleaner
914 /// **Known problems:** None.
918 /// let some_vec = vec![0, 1, 2, 3];
919 /// let bad_vec = some_vec.iter().skip(3).next();
920 /// let bad_slice = &some_vec[..].iter().skip(3).next();
922 /// The correct use would be:
924 /// let some_vec = vec![0, 1, 2, 3];
925 /// let bad_vec = some_vec.iter().nth(3);
926 /// let bad_slice = &some_vec[..].iter().nth(3);
930 "using `.skip(x).next()` on an iterator"
933 declare_clippy_lint! {
934 /// **What it does:** Checks for use of `.get().unwrap()` (or
935 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
937 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
940 /// **Known problems:** Not a replacement for error handling: Using either
941 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
942 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
943 /// temporary placeholder for dealing with the `Option` type, then this does
944 /// not mitigate the need for error handling. If there is a chance that `.get()`
945 /// will be `None` in your program, then it is advisable that the `None` case
946 /// is handled in a future refactor instead of using `.unwrap()` or the Index
951 /// let mut some_vec = vec![0, 1, 2, 3];
952 /// let last = some_vec.get(3).unwrap();
953 /// *some_vec.get_mut(0).unwrap() = 1;
955 /// The correct use would be:
957 /// let mut some_vec = vec![0, 1, 2, 3];
958 /// let last = some_vec[3];
963 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
966 declare_clippy_lint! {
967 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
968 /// `&str` or `String`.
970 /// **Why is this bad?** `.push_str(s)` is clearer
972 /// **Known problems:** None.
977 /// let def = String::from("def");
978 /// let mut s = String::new();
979 /// s.extend(abc.chars());
980 /// s.extend(def.chars());
982 /// The correct use would be:
985 /// let def = String::from("def");
986 /// let mut s = String::new();
988 /// s.push_str(&def);
990 pub STRING_EXTEND_CHARS,
992 "using `x.extend(s.chars())` where s is a `&str` or `String`"
995 declare_clippy_lint! {
996 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
999 /// **Why is this bad?** `.to_vec()` is clearer
1001 /// **Known problems:** None.
1005 /// let s = [1, 2, 3, 4, 5];
1006 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
1008 /// The better use would be:
1010 /// let s = [1, 2, 3, 4, 5];
1011 /// let s2: Vec<isize> = s.to_vec();
1013 pub ITER_CLONED_COLLECT,
1015 "using `.cloned().collect()` on slice to create a `Vec`"
1018 declare_clippy_lint! {
1019 /// **What it does:** Checks for usage of `_.chars().last()` or
1020 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1022 /// **Why is this bad?** Readability, this can be written more concisely as
1023 /// `_.ends_with(_)`.
1025 /// **Known problems:** None.
1029 /// # let name = "_";
1032 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1035 /// name.ends_with('_') || name.ends_with('-');
1039 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1042 declare_clippy_lint! {
1043 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
1044 /// types before and after the call are the same.
1046 /// **Why is this bad?** The call is unnecessary.
1048 /// **Known problems:** None.
1052 /// # fn do_stuff(x: &[i32]) {}
1053 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1054 /// do_stuff(x.as_ref());
1056 /// The correct use would be:
1058 /// # fn do_stuff(x: &[i32]) {}
1059 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1064 "using `as_ref` where the types before and after the call are the same"
1067 declare_clippy_lint! {
1068 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1069 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1070 /// `sum` or `product`.
1072 /// **Why is this bad?** Readability.
1074 /// **Known problems:** None.
1078 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1080 /// This could be written as:
1082 /// let _ = (0..3).any(|x| x > 2);
1084 pub UNNECESSARY_FOLD,
1086 "using `fold` when a more succinct alternative exists"
1089 declare_clippy_lint! {
1090 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1091 /// More specifically it checks if the closure provided is only performing one of the
1092 /// filter or map operations and suggests the appropriate option.
1094 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1095 /// operation is being performed.
1097 /// **Known problems:** None
1101 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1103 /// // As there is no transformation of the argument this could be written as:
1104 /// let _ = (0..3).filter(|&x| x > 2);
1108 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1110 /// // As there is no conditional check on the argument this could be written as:
1111 /// let _ = (0..4).map(|x| x + 1);
1113 pub UNNECESSARY_FILTER_MAP,
1115 "using `filter_map` when a more succinct alternative exists"
1118 declare_clippy_lint! {
1119 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1122 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1123 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1124 /// `iter_mut` directly.
1126 /// **Known problems:** None
1132 /// let _ = (&vec![3, 4, 5]).into_iter();
1135 /// let _ = (&vec![3, 4, 5]).iter();
1137 pub INTO_ITER_ON_REF,
1139 "using `.into_iter()` on a reference"
1142 declare_clippy_lint! {
1143 /// **What it does:** Checks for calls to `map` followed by a `count`.
1145 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1146 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1147 /// drive the iterator to completion, you can just use `for_each` instead.
1149 /// **Known problems:** None
1154 /// let _ = (0..3).map(|x| x + 2).count();
1158 "suspicious usage of map"
1161 declare_clippy_lint! {
1162 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1164 /// **Why is this bad?** For most types, this is undefined behavior.
1166 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1167 /// of `MaybeUninit`. There may be other types that allow uninitialized
1168 /// data, but those are not yet rigorously defined.
1173 /// // Beware the UB
1174 /// use std::mem::MaybeUninit;
1176 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1179 /// Note that the following is OK:
1182 /// use std::mem::MaybeUninit;
1184 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1185 /// MaybeUninit::uninit().assume_init()
1188 pub UNINIT_ASSUMED_INIT,
1190 "`MaybeUninit::uninit().assume_init()`"
1193 declare_clippy_lint! {
1194 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1196 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1201 /// # let y: u32 = 0;
1202 /// # let x: u32 = 100;
1203 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1204 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1207 /// can be written using dedicated methods for saturating addition/subtraction as:
1210 /// # let y: u32 = 0;
1211 /// # let x: u32 = 100;
1212 /// let add = x.saturating_add(y);
1213 /// let sub = x.saturating_sub(y);
1215 pub MANUAL_SATURATING_ARITHMETIC,
1217 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1220 declare_clippy_lint! {
1221 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1222 /// zero-sized types
1224 /// **Why is this bad?** This is a no-op, and likely unintended
1226 /// **Known problems:** None
1230 /// unsafe { (&() as *const ()).offset(1) };
1234 "Check for offset calculations on raw pointers to zero-sized types"
1237 declare_clippy_lint! {
1238 /// **What it does:** Checks for `FileType::is_file()`.
1240 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1241 /// they are testing whether a path is something they can get bytes from. But
1242 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1243 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1249 /// let metadata = std::fs::metadata("foo.txt")?;
1250 /// let filetype = metadata.file_type();
1252 /// if filetype.is_file() {
1255 /// # Ok::<_, std::io::Error>(())
1259 /// should be written as:
1263 /// let metadata = std::fs::metadata("foo.txt")?;
1264 /// let filetype = metadata.file_type();
1266 /// if !filetype.is_dir() {
1269 /// # Ok::<_, std::io::Error>(())
1272 pub FILETYPE_IS_FILE,
1274 "`FileType::is_file` is not recommended to test for readable file type"
1277 declare_clippy_lint! {
1278 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1280 /// **Why is this bad?** Readability, this can be written more concisely as
1283 /// **Known problems:** None.
1287 /// # let opt = Some("".to_string());
1288 /// opt.as_ref().map(String::as_str)
1291 /// Can be written as
1293 /// # let opt = Some("".to_string());
1297 pub OPTION_AS_REF_DEREF,
1299 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1302 declare_clippy_lint! {
1303 /// **What it does:** Checks for usage of `iter().next()` on a Slice or an Array
1305 /// **Why is this bad?** These can be shortened into `.get()`
1307 /// **Known problems:** None.
1311 /// # let a = [1, 2, 3];
1312 /// # let b = vec![1, 2, 3];
1313 /// a[2..].iter().next();
1314 /// b.iter().next();
1316 /// should be written as:
1318 /// # let a = [1, 2, 3];
1319 /// # let b = vec![1, 2, 3];
1323 pub ITER_NEXT_SLICE,
1325 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1328 declare_clippy_lint! {
1329 /// **What it does:** Warns when using `push_str`/`insert_str` with a single-character string literal
1330 /// where `push`/`insert` with a `char` would work fine.
1332 /// **Why is this bad?** It's less clear that we are pushing a single character.
1334 /// **Known problems:** None
1338 /// let mut string = String::new();
1339 /// string.insert_str(0, "R");
1340 /// string.push_str("R");
1342 /// Could be written as
1344 /// let mut string = String::new();
1345 /// string.insert(0, 'R');
1346 /// string.push('R');
1348 pub SINGLE_CHAR_ADD_STR,
1350 "`push_str()` or `insert_str()` used with a single-character string literal as parameter"
1353 declare_clippy_lint! {
1354 /// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1355 /// lazily evaluated closures on `Option` and `Result`.
1357 /// This lint suggests changing the following functions, when eager evaluation results in
1359 /// - `unwrap_or_else` to `unwrap_or`
1360 /// - `and_then` to `and`
1361 /// - `or_else` to `or`
1362 /// - `get_or_insert_with` to `get_or_insert`
1363 /// - `ok_or_else` to `ok_or`
1365 /// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1367 /// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1368 /// side effects. Eagerly evaluating them can change the semantics of the program.
1373 /// // example code where clippy issues a warning
1374 /// let opt: Option<u32> = None;
1376 /// opt.unwrap_or_else(|| 42);
1380 /// let opt: Option<u32> = None;
1382 /// opt.unwrap_or(42);
1384 pub UNNECESSARY_LAZY_EVALUATIONS,
1386 "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1389 declare_clippy_lint! {
1390 /// **What it does:** Checks for usage of `_.map(_).collect::<Result<(), _>()`.
1392 /// **Why is this bad?** Using `try_for_each` instead is more readable and idiomatic.
1394 /// **Known problems:** None
1399 /// (0..3).map(|t| Err(t)).collect::<Result<(), _>>();
1403 /// (0..3).try_for_each(|t| Err(t));
1405 pub MAP_COLLECT_RESULT_UNIT,
1407 "using `.map(_).collect::<Result<(),_>()`, which can be replaced with `try_for_each`"
1410 declare_clippy_lint! {
1411 /// **What it does:** Checks for `from_iter()` function calls on types that implement the `FromIterator`
1414 /// **Why is this bad?** It is recommended style to use collect. See
1415 /// [FromIterator documentation](https://doc.rust-lang.org/std/iter/trait.FromIterator.html)
1417 /// **Known problems:** None.
1422 /// use std::iter::FromIterator;
1424 /// let five_fives = std::iter::repeat(5).take(5);
1426 /// let v = Vec::from_iter(five_fives);
1428 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1432 /// let five_fives = std::iter::repeat(5).take(5);
1434 /// let v: Vec<i32> = five_fives.collect();
1436 /// assert_eq!(v, vec![5, 5, 5, 5, 5]);
1438 pub FROM_ITER_INSTEAD_OF_COLLECT,
1440 "use `.collect()` instead of `::from_iter()`"
1443 declare_clippy_lint! {
1444 /// **What it does:** Checks for usage of `inspect().for_each()`.
1446 /// **Why is this bad?** It is the same as performing the computation
1447 /// inside `inspect` at the beginning of the closure in `for_each`.
1449 /// **Known problems:** None.
1454 /// [1,2,3,4,5].iter()
1455 /// .inspect(|&x| println!("inspect the number: {}", x))
1456 /// .for_each(|&x| {
1457 /// assert!(x >= 0);
1460 /// Can be written as
1462 /// [1,2,3,4,5].iter()
1463 /// .for_each(|&x| {
1464 /// println!("inspect the number: {}", x);
1465 /// assert!(x >= 0);
1468 pub INSPECT_FOR_EACH,
1470 "using `.inspect().for_each()`, which can be replaced with `.for_each()`"
1473 declare_clippy_lint! {
1474 /// **What it does:** Checks for usage of `filter_map(|x| x)`.
1476 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
1478 /// **Known problems:** None.
1483 /// # let iter = vec![Some(1)].into_iter();
1484 /// iter.filter_map(|x| x);
1488 /// # let iter = vec![Some(1)].into_iter();
1491 pub FILTER_MAP_IDENTITY,
1493 "call to `filter_map` where `flatten` is sufficient"
1496 declare_clippy_lint! {
1497 /// **What it does:** Checks for the use of `.bytes().nth()`.
1499 /// **Why is this bad?** `.as_bytes().get()` is more efficient and more
1502 /// **Known problems:** None.
1508 /// let _ = "Hello".bytes().nth(3);
1511 /// let _ = "Hello".as_bytes().get(3);
1515 "replace `.bytes().nth()` with `.as_bytes().get()`"
1518 declare_clippy_lint! {
1519 /// **What it does:** Checks for the usage of `_.to_owned()`, `vec.to_vec()`, or similar when calling `_.clone()` would be clearer.
1521 /// **Why is this bad?** These methods do the same thing as `_.clone()` but may be confusing as
1522 /// to why we are calling `to_vec` on something that is already a `Vec` or calling `to_owned` on something that is already owned.
1524 /// **Known problems:** None.
1529 /// let a = vec![1, 2, 3];
1530 /// let b = a.to_vec();
1531 /// let c = a.to_owned();
1535 /// let a = vec![1, 2, 3];
1536 /// let b = a.clone();
1537 /// let c = a.clone();
1541 "implicitly cloning a value by invoking a function on its dereferenced type"
1544 declare_clippy_lint! {
1545 /// **What it does:** Checks for the use of `.iter().count()`.
1547 /// **Why is this bad?** `.len()` is more efficient and more
1550 /// **Known problems:** None.
1556 /// let some_vec = vec![0, 1, 2, 3];
1557 /// let _ = some_vec.iter().count();
1558 /// let _ = &some_vec[..].iter().count();
1561 /// let some_vec = vec![0, 1, 2, 3];
1562 /// let _ = some_vec.len();
1563 /// let _ = &some_vec[..].len();
1567 "replace `.iter().count()` with `.len()`"
1570 pub struct Methods {
1571 msrv: Option<RustcVersion>,
1576 pub fn new(msrv: Option<RustcVersion>) -> Self {
1581 impl_lint_pass!(Methods => [
1584 SHOULD_IMPLEMENT_TRAIT,
1585 WRONG_SELF_CONVENTION,
1586 WRONG_PUB_SELF_CONVENTION,
1589 RESULT_MAP_OR_INTO_OPTION,
1591 BIND_INSTEAD_OF_MAP,
1599 INEFFICIENT_TO_STRING,
1601 SINGLE_CHAR_PATTERN,
1602 SINGLE_CHAR_ADD_STR,
1607 FILTER_MAP_IDENTITY,
1613 ITERATOR_STEP_BY_ZERO,
1621 STRING_EXTEND_CHARS,
1622 ITER_CLONED_COLLECT,
1625 UNNECESSARY_FILTER_MAP,
1628 UNINIT_ASSUMED_INIT,
1629 MANUAL_SATURATING_ARITHMETIC,
1632 OPTION_AS_REF_DEREF,
1633 UNNECESSARY_LAZY_EVALUATIONS,
1634 MAP_COLLECT_RESULT_UNIT,
1635 FROM_ITER_INSTEAD_OF_COLLECT,
1640 impl<'tcx> LateLintPass<'tcx> for Methods {
1641 #[allow(clippy::too_many_lines)]
1642 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1643 if in_macro(expr.span) {
1647 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1648 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1649 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1651 match method_names.as_slice() {
1652 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1653 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1654 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1655 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1656 ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1657 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1658 ["unwrap_or_else", "map"] => {
1659 if !lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0], self.msrv.as_ref()) {
1660 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or");
1663 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1664 ["and_then", ..] => {
1665 let biom_option_linted = bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
1666 let biom_result_linted = bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
1667 if !biom_option_linted && !biom_result_linted {
1668 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "and");
1671 ["or_else", ..] => {
1672 if !bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]) {
1673 unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "or");
1676 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1677 ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1678 ["next", "iter"] => lint_iter_next(cx, expr, arg_lists[1]),
1679 ["map", "filter"] => lint_filter_map(cx, expr, false),
1680 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1681 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1], self.msrv.as_ref()),
1682 ["map", "find"] => lint_filter_map(cx, expr, true),
1683 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1684 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1685 ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1686 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1687 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1688 ["is_some", "position"] => {
1689 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1691 ["is_some", "rposition"] => {
1692 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1694 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1695 ["count", "into_iter"] => iter_count::lints(cx, expr, &arg_lists[1], "into_iter"),
1696 ["count", "iter"] => iter_count::lints(cx, expr, &arg_lists[1], "iter"),
1697 ["count", "iter_mut"] => iter_count::lints(cx, expr, &arg_lists[1], "iter_mut"),
1698 ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1699 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1700 ["nth", "bytes"] => bytes_nth::lints(cx, expr, &arg_lists[1]),
1701 ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1702 ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1703 ["next", "skip"] => lint_iter_skip_next(cx, expr, arg_lists[1]),
1704 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1705 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1706 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1707 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1708 ["filter_map", ..] => {
1709 unnecessary_filter_map::lint(cx, expr, arg_lists[0]);
1710 filter_map_identity::check(cx, expr, arg_lists[0], method_spans[0]);
1712 ["count", "map"] => lint_suspicious_map(cx, expr),
1713 ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1714 ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
1715 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1717 ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
1718 check_pointer_offset(cx, expr, arg_lists[0])
1720 ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1721 ["map", "as_ref"] => {
1722 lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false, self.msrv.as_ref())
1724 ["map", "as_mut"] => {
1725 lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true, self.msrv.as_ref())
1727 ["unwrap_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "unwrap_or"),
1728 ["get_or_insert_with", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "get_or_insert"),
1729 ["ok_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], "ok_or"),
1730 ["collect", "map"] => lint_map_collect(cx, expr, arg_lists[1], arg_lists[0]),
1731 ["for_each", "inspect"] => inspect_for_each::lint(cx, expr, method_spans[1]),
1732 ["to_owned", ..] => implicit_clone::check(cx, expr, sym::ToOwned),
1733 ["to_os_string", ..] => implicit_clone::check(cx, expr, sym::OsStr),
1734 ["to_path_buf", ..] => implicit_clone::check(cx, expr, sym::Path),
1735 ["to_vec", ..] => implicit_clone::check(cx, expr, sym::slice),
1740 hir::ExprKind::Call(ref func, ref args) => {
1741 if let hir::ExprKind::Path(path) = &func.kind {
1742 if match_qpath(path, &["from_iter"]) {
1743 lint_from_iter(cx, expr, args);
1747 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
1748 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1749 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1751 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
1752 if args.len() == 1 && method_call.ident.name == sym::clone {
1753 lint_clone_on_copy(cx, expr, &args[0], self_ty);
1754 lint_clone_on_ref_ptr(cx, expr, &args[0]);
1756 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1757 inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1760 if let Some(fn_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) {
1761 if match_def_path(cx, fn_def_id, &paths::PUSH_STR) {
1762 lint_single_char_push_string(cx, expr, args);
1763 } else if match_def_path(cx, fn_def_id, &paths::INSERT_STR) {
1764 lint_single_char_insert_string(cx, expr, args);
1768 match self_ty.kind() {
1769 ty::Ref(_, ty, _) if *ty.kind() == ty::Str => {
1770 for &(method, pos) in &PATTERN_METHODS {
1771 if method_call.ident.name.as_str() == method && args.len() > pos {
1772 lint_single_char_pattern(cx, expr, &args[pos]);
1776 ty::Ref(..) if method_call.ident.name == sym::into_iter => {
1777 lint_into_iter(cx, expr, self_ty, *method_span);
1782 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1783 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1785 let mut info = BinaryExprInfo {
1789 eq: op.node == hir::BinOpKind::Eq,
1791 lint_binary_expr_with_method_call(cx, &mut info);
1797 #[allow(clippy::too_many_lines)]
1798 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1799 if in_external_macro(cx.sess(), impl_item.span) {
1802 let name = impl_item.ident.name.as_str();
1803 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id());
1804 let item = cx.tcx.hir().expect_item(parent);
1805 let self_ty = cx.tcx.type_of(item.def_id);
1807 // if this impl block implements a trait, lint in trait definition instead
1808 if let hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind {
1813 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1814 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1816 let method_sig = cx.tcx.fn_sig(impl_item.def_id);
1817 let method_sig = cx.tcx.erase_late_bound_regions(method_sig);
1819 let first_arg_ty = &method_sig.inputs().iter().next();
1821 // check conventions w.r.t. conversion method names and predicates
1822 if let Some(first_arg_ty) = first_arg_ty;
1825 if cx.access_levels.is_exported(impl_item.hir_id()) {
1826 // check missing trait implementations
1827 for method_config in &TRAIT_METHODS {
1828 if name == method_config.method_name &&
1829 sig.decl.inputs.len() == method_config.param_count &&
1830 method_config.output_type.matches(cx, &sig.decl.output) &&
1831 method_config.self_kind.matches(cx, self_ty, first_arg_ty) &&
1832 fn_header_equals(method_config.fn_header, sig.header) &&
1833 method_config.lifetime_param_cond(&impl_item)
1837 SHOULD_IMPLEMENT_TRAIT,
1840 "method `{}` can be confused for the standard trait method `{}::{}`",
1841 method_config.method_name,
1842 method_config.trait_name,
1843 method_config.method_name
1847 "consider implementing the trait `{}` or choosing a less ambiguous method name",
1848 method_config.trait_name
1855 lint_wrong_self_convention(
1858 item.vis.node.is_pub(),
1866 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1867 let ret_ty = return_ty(cx, impl_item.hir_id());
1869 // walk the return type and check for Self (this does not check associated types)
1870 if contains_ty(ret_ty, self_ty) {
1874 // if return type is impl trait, check the associated types
1875 if let ty::Opaque(def_id, _) = *ret_ty.kind() {
1876 // one of the associated types must be Self
1877 for &(predicate, _span) in cx.tcx.explicit_item_bounds(def_id) {
1878 if let ty::PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1879 // walk the associated type and check for Self
1880 if contains_ty(projection_predicate.ty, self_ty) {
1887 if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1892 "methods called `new` usually return `Self`",
1898 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
1899 if in_external_macro(cx.tcx.sess, item.span) {
1904 if let TraitItemKind::Fn(ref sig, _) = item.kind;
1905 if let Some(first_arg_ty) = sig.decl.inputs.iter().next();
1906 let first_arg_span = first_arg_ty.span;
1907 let first_arg_ty = hir_ty_to_ty(cx.tcx, first_arg_ty);
1908 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1911 lint_wrong_self_convention(cx, &item.ident.name.as_str(), false, self_ty, first_arg_ty, first_arg_span);
1916 if item.ident.name == sym::new;
1917 if let TraitItemKind::Fn(_, _) = item.kind;
1918 let ret_ty = return_ty(cx, item.hir_id());
1919 let self_ty = TraitRef::identity(cx.tcx, item.def_id.to_def_id()).self_ty();
1920 if !contains_ty(ret_ty, self_ty);
1927 "methods called `new` usually return `Self`",
1933 extract_msrv_attr!(LateContext);
1936 fn lint_wrong_self_convention<'tcx>(
1937 cx: &LateContext<'tcx>,
1940 self_ty: &'tcx TyS<'tcx>,
1941 first_arg_ty: &'tcx TyS<'tcx>,
1942 first_arg_span: Span,
1944 let lint = if is_pub {
1945 WRONG_PUB_SELF_CONVENTION
1947 WRONG_SELF_CONVENTION
1949 if let Some((ref conv, self_kinds)) = &CONVENTIONS.iter().find(|(ref conv, _)| conv.check(item_name)) {
1950 if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
1956 "methods called `{}` usually take {}; consider choosing a less ambiguous name",
1960 .map(|k| k.description())
1961 .collect::<Vec<_>>()
1969 /// Checks for the `OR_FUN_CALL` lint.
1970 #[allow(clippy::too_many_lines)]
1971 fn lint_or_fun_call<'tcx>(
1972 cx: &LateContext<'tcx>,
1973 expr: &hir::Expr<'_>,
1976 args: &'tcx [hir::Expr<'_>],
1978 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1979 fn check_unwrap_or_default(
1980 cx: &LateContext<'_>,
1982 fun: &hir::Expr<'_>,
1983 self_expr: &hir::Expr<'_>,
1984 arg: &hir::Expr<'_>,
1990 if name == "unwrap_or";
1991 if let hir::ExprKind::Path(ref qpath) = fun.kind;
1992 let path = &*last_path_segment(qpath).ident.as_str();
1993 if ["default", "new"].contains(&path);
1994 let arg_ty = cx.typeck_results().expr_ty(arg);
1995 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1996 if implements_trait(cx, arg_ty, default_trait_id, &[]);
1999 let mut applicability = Applicability::MachineApplicable;
2004 &format!("use of `{}` followed by a call to `{}`", name, path),
2007 "{}.unwrap_or_default()",
2008 snippet_with_applicability(cx, self_expr.span, "..", &mut applicability)
2020 /// Checks for `*or(foo())`.
2021 #[allow(clippy::too_many_arguments)]
2022 fn check_general_case<'tcx>(
2023 cx: &LateContext<'tcx>,
2026 self_expr: &hir::Expr<'_>,
2027 arg: &'tcx hir::Expr<'_>,
2029 // None if lambda is required
2030 fun_span: Option<Span>,
2032 // (path, fn_has_argument, methods, suffix)
2033 static KNOW_TYPES: [(&[&str], bool, &[&str], &str); 4] = [
2034 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
2035 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
2036 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
2037 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
2040 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind {
2041 if path.ident.as_str() == "len" {
2042 let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
2045 ty::Slice(_) | ty::Array(_, _) => return,
2049 if is_type_diagnostic_item(cx, ty, sym::vec_type) {
2056 if KNOW_TYPES.iter().any(|k| k.2.contains(&name));
2058 if is_lazyness_candidate(cx, arg);
2059 if !contains_return(&arg);
2061 let self_ty = cx.typeck_results().expr_ty(self_expr);
2063 if let Some(&(_, fn_has_arguments, poss, suffix)) =
2064 KNOW_TYPES.iter().find(|&&i| match_type(cx, self_ty, i.0));
2066 if poss.contains(&name);
2069 let macro_expanded_snipped;
2070 let sugg: Cow<'_, str> = {
2071 let (snippet_span, use_lambda) = match (fn_has_arguments, fun_span) {
2072 (false, Some(fun_span)) => (fun_span, false),
2073 _ => (arg.span, true),
2076 let not_macro_argument_snippet = snippet_with_macro_callsite(cx, snippet_span, "..");
2077 if not_macro_argument_snippet == "vec![]" {
2078 macro_expanded_snipped = snippet(cx, snippet_span, "..");
2079 match macro_expanded_snipped.strip_prefix("$crate::vec::") {
2080 Some(stripped) => Cow::from(stripped),
2081 None => macro_expanded_snipped
2085 not_macro_argument_snippet
2090 let l_arg = if fn_has_arguments { "_" } else { "" };
2091 format!("|{}| {}", l_arg, snippet).into()
2096 let span_replace_word = method_span.with_hi(span.hi());
2101 &format!("use of `{}` followed by a function call", name),
2103 format!("{}_{}({})", name, suffix, sugg),
2104 Applicability::HasPlaceholders,
2110 if args.len() == 2 {
2111 match args[1].kind {
2112 hir::ExprKind::Call(ref fun, ref or_args) => {
2113 let or_has_args = !or_args.is_empty();
2114 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
2115 let fun_span = if or_has_args { None } else { Some(fun.span) };
2116 check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, fun_span);
2119 hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => {
2120 check_general_case(cx, name, method_span, &args[0], &args[1], expr.span, None);
2127 /// Checks for the `EXPECT_FUN_CALL` lint.
2128 #[allow(clippy::too_many_lines)]
2129 fn lint_expect_fun_call(
2130 cx: &LateContext<'_>,
2131 expr: &hir::Expr<'_>,
2134 args: &[hir::Expr<'_>],
2136 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
2138 fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
2139 let mut arg_root = arg;
2141 arg_root = match &arg_root.kind {
2142 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
2143 hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
2144 if call_args.len() == 1
2145 && (method_name.ident.name == sym::as_str || method_name.ident.name == sym!(as_ref))
2147 let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
2148 let base_type = arg_type.peel_refs();
2149 *base_type.kind() == ty::Str || is_type_diagnostic_item(cx, base_type, sym::string_type)
2163 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
2164 // converted to string.
2165 fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
2166 let arg_ty = cx.typeck_results().expr_ty(arg);
2167 if is_type_diagnostic_item(cx, arg_ty, sym::string_type) {
2170 if let ty::Ref(_, ty, ..) = arg_ty.kind() {
2171 if *ty.kind() == ty::Str && can_be_static_str(cx, arg) {
2178 // Check if an expression could have type `&'static str`, knowing that it
2179 // has type `&str` for some lifetime.
2180 fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
2182 hir::ExprKind::Lit(_) => true,
2183 hir::ExprKind::Call(fun, _) => {
2184 if let hir::ExprKind::Path(ref p) = fun.kind {
2185 match cx.qpath_res(p, fun.hir_id) {
2186 hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
2187 cx.tcx.fn_sig(def_id).output().skip_binder().kind(),
2188 ty::Ref(ty::ReStatic, ..)
2196 hir::ExprKind::MethodCall(..) => {
2198 .type_dependent_def_id(arg.hir_id)
2199 .map_or(false, |method_id| {
2201 cx.tcx.fn_sig(method_id).output().skip_binder().kind(),
2202 ty::Ref(ty::ReStatic, ..)
2206 hir::ExprKind::Path(ref p) => matches!(
2207 cx.qpath_res(p, arg.hir_id),
2208 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
2214 fn generate_format_arg_snippet(
2215 cx: &LateContext<'_>,
2217 applicability: &mut Applicability,
2220 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
2221 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
2222 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
2227 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
2235 fn is_call(node: &hir::ExprKind<'_>) -> bool {
2237 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
2240 hir::ExprKind::Call(..)
2241 | hir::ExprKind::MethodCall(..)
2242 // These variants are debatable or require further examination
2243 | hir::ExprKind::If(..)
2244 | hir::ExprKind::Match(..)
2245 | hir::ExprKind::Block{ .. } => true,
2250 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
2254 let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
2255 let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym::option_type) {
2257 } else if is_type_diagnostic_item(cx, receiver_type, sym::result_type) {
2263 let arg_root = get_arg_root(cx, &args[1]);
2265 let span_replace_word = method_span.with_hi(expr.span.hi());
2267 let mut applicability = Applicability::MachineApplicable;
2269 //Special handling for `format!` as arg_root
2271 if let hir::ExprKind::Block(block, None) = &arg_root.kind;
2272 if block.stmts.len() == 1;
2273 if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
2274 if let Some(arg_root) = &local.init;
2275 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
2276 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
2277 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
2279 let fmt_spec = &format_args[0];
2280 let fmt_args = &format_args[1];
2282 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
2284 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
2286 let sugg = args.join(", ");
2292 &format!("use of `{}` followed by a function call", name),
2294 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
2302 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
2303 if requires_to_string(cx, arg_root) {
2304 arg_root_snippet.to_mut().push_str(".to_string()");
2311 &format!("use of `{}` followed by a function call", name),
2314 "unwrap_or_else({} {{ panic!(\"{{}}\", {}) }})",
2315 closure_args, arg_root_snippet
2321 /// Checks for the `CLONE_ON_COPY` lint.
2322 fn lint_clone_on_copy(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
2323 let ty = cx.typeck_results().expr_ty(expr);
2324 if let ty::Ref(_, inner, _) = arg_ty.kind() {
2325 if let ty::Ref(_, innermost, _) = inner.kind() {
2331 "using `clone` on a double-reference; \
2332 this will copy the reference of type `{}` instead of cloning the inner type",
2336 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
2337 let mut ty = innermost;
2339 while let ty::Ref(_, inner, _) = ty.kind() {
2343 let refs: String = iter::repeat('&').take(n + 1).collect();
2344 let derefs: String = iter::repeat('*').take(n).collect();
2345 let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
2346 diag.span_suggestion(
2348 "try dereferencing it",
2349 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
2350 Applicability::MaybeIncorrect,
2352 diag.span_suggestion(
2354 "or try being explicit if you are sure, that you want to clone a reference",
2356 Applicability::MaybeIncorrect,
2361 return; // don't report clone_on_copy
2365 if is_copy(cx, ty) {
2367 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
2368 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
2369 match &cx.tcx.hir().get(parent) {
2370 hir::Node::Expr(parent) => match parent.kind {
2371 // &*x is a nop, &x.clone() is not
2372 hir::ExprKind::AddrOf(..) => return,
2373 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
2374 hir::ExprKind::MethodCall(_, _, parent_args, _) if expr.hir_id == parent_args[0].hir_id => {
2380 hir::Node::Stmt(stmt) => {
2381 if let hir::StmtKind::Local(ref loc) = stmt.kind {
2382 if let hir::PatKind::Ref(..) = loc.pat.kind {
2383 // let ref y = *x borrows x, let ref y = x.clone() does not
2391 // x.clone() might have dereferenced x, possibly through Deref impls
2392 if cx.typeck_results().expr_ty(arg) == ty {
2393 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
2395 let deref_count = cx
2397 .expr_adjustments(arg)
2399 .filter(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
2401 let derefs: String = iter::repeat('*').take(deref_count).collect();
2402 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
2411 &format!("using `clone` on type `{}` which implements the `Copy` trait", ty),
2413 if let Some((text, snip)) = snip {
2414 diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable);
2421 fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
2422 let obj_ty = cx.typeck_results().expr_ty(arg).peel_refs();
2424 if let ty::Adt(_, subst) = obj_ty.kind() {
2425 let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
2427 } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
2429 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
2435 let snippet = snippet_with_macro_callsite(cx, arg.span, "..");
2441 "using `.clone()` on a ref-counted pointer",
2443 format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
2444 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
2449 fn lint_string_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2451 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2452 let target = &arglists[0][0];
2453 let self_ty = cx.typeck_results().expr_ty(target).peel_refs();
2454 let ref_str = if *self_ty.kind() == ty::Str {
2456 } else if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
2462 let mut applicability = Applicability::MachineApplicable;
2465 STRING_EXTEND_CHARS,
2467 "calling `.extend(_.chars())`",
2470 "{}.push_str({}{})",
2471 snippet_with_applicability(cx, args[0].span, "..", &mut applicability),
2473 snippet_with_applicability(cx, target.span, "..", &mut applicability)
2480 fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2481 let obj_ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
2482 if is_type_diagnostic_item(cx, obj_ty, sym::string_type) {
2483 lint_string_extend(cx, expr, args);
2487 fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2489 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::vec_type);
2490 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0]));
2491 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2496 ITER_CLONED_COLLECT,
2498 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2501 ".to_vec()".to_string(),
2502 Applicability::MachineApplicable,
2508 fn lint_unnecessary_fold(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2509 fn check_fold_with_op(
2510 cx: &LateContext<'_>,
2511 expr: &hir::Expr<'_>,
2512 fold_args: &[hir::Expr<'_>],
2515 replacement_method_name: &str,
2516 replacement_has_args: bool,
2519 // Extract the body of the closure passed to fold
2520 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2521 let closure_body = cx.tcx.hir().body(body_id);
2522 let closure_expr = remove_blocks(&closure_body.value);
2524 // Check if the closure body is of the form `acc <op> some_expr(x)`
2525 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2526 if bin_op.node == op;
2528 // Extract the names of the two arguments to the closure
2529 if let [param_a, param_b] = closure_body.params;
2530 if let PatKind::Binding(_, first_arg_id, ..) = strip_pat_refs(¶m_a.pat).kind;
2531 if let PatKind::Binding(_, second_arg_id, second_arg_ident, _) = strip_pat_refs(¶m_b.pat).kind;
2533 if path_to_local_id(left_expr, first_arg_id);
2534 if replacement_has_args || path_to_local_id(right_expr, second_arg_id);
2537 let mut applicability = Applicability::MachineApplicable;
2538 let sugg = if replacement_has_args {
2540 "{replacement}(|{s}| {r})",
2541 replacement = replacement_method_name,
2542 s = second_arg_ident,
2543 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2548 replacement = replacement_method_name,
2555 fold_span.with_hi(expr.span.hi()),
2556 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2557 "this `.fold` can be written more succinctly using another method",
2566 // Check that this is a call to Iterator::fold rather than just some function called fold
2567 if !match_trait_method(cx, expr, &paths::ITERATOR) {
2572 fold_args.len() == 3,
2573 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2576 // Check if the first argument to .fold is a suitable literal
2577 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2579 ast::LitKind::Bool(false) => {
2580 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2582 ast::LitKind::Bool(true) => {
2583 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2585 ast::LitKind::Int(0, _) => {
2586 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2588 ast::LitKind::Int(1, _) => {
2589 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2596 fn lint_step_by<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2597 if match_trait_method(cx, expr, &paths::ITERATOR) {
2598 if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &args[1]) {
2601 ITERATOR_STEP_BY_ZERO,
2603 "Iterator::step_by(0) will panic at runtime",
2609 fn lint_iter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2610 let caller_expr = &iter_args[0];
2612 // Skip lint if the `iter().next()` expression is a for loop argument,
2613 // since it is already covered by `&loops::ITER_NEXT_LOOP`
2614 let mut parent_expr_opt = get_parent_expr(cx, expr);
2615 while let Some(parent_expr) = parent_expr_opt {
2616 if higher::for_loop(parent_expr).is_some() {
2619 parent_expr_opt = get_parent_expr(cx, parent_expr);
2622 if derefs_to_slice(cx, caller_expr, cx.typeck_results().expr_ty(caller_expr)).is_some() {
2623 // caller is a Slice
2625 if let hir::ExprKind::Index(ref caller_var, ref index_expr) = &caller_expr.kind;
2626 if let Some(higher::Range { start: Some(start_expr), end: None, limits: ast::RangeLimits::HalfOpen })
2627 = higher::range(index_expr);
2628 if let hir::ExprKind::Lit(ref start_lit) = &start_expr.kind;
2629 if let ast::LitKind::Int(start_idx, _) = start_lit.node;
2631 let mut applicability = Applicability::MachineApplicable;
2636 "using `.iter().next()` on a Slice without end index",
2638 format!("{}.get({})", snippet_with_applicability(cx, caller_var.span, "..", &mut applicability), start_idx),
2643 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(caller_expr), sym::vec_type)
2645 &cx.typeck_results().expr_ty(caller_expr).peel_refs().kind(),
2649 // caller is a Vec or an Array
2650 let mut applicability = Applicability::MachineApplicable;
2655 "using `.iter().next()` on an array",
2659 snippet_with_applicability(cx, caller_expr.span, "..", &mut applicability)
2666 fn lint_iter_nth<'tcx>(
2667 cx: &LateContext<'tcx>,
2668 expr: &hir::Expr<'_>,
2669 nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2672 let iter_args = nth_and_iter_args[1];
2673 let mut_str = if is_mut { "_mut" } else { "" };
2674 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])).is_some() {
2676 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym::vec_type) {
2678 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vecdeque_type)) {
2681 let nth_args = nth_and_iter_args[0];
2682 lint_iter_nth_zero(cx, expr, &nth_args);
2683 return; // caller is not a type that we want to lint
2690 &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2692 &format!("calling `.get{}()` is both faster and more readable", mut_str),
2696 fn lint_iter_nth_zero<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2698 if match_trait_method(cx, expr, &paths::ITERATOR);
2699 if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &nth_args[1]);
2701 let mut applicability = Applicability::MachineApplicable;
2706 "called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent",
2707 "try calling `.next()` instead of `.nth(0)`",
2708 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2715 fn lint_get_unwrap<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args: &'tcx [hir::Expr<'_>], is_mut: bool) {
2716 // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2717 // because they do not implement `IndexMut`
2718 let mut applicability = Applicability::MachineApplicable;
2719 let expr_ty = cx.typeck_results().expr_ty(&get_args[0]);
2720 let get_args_str = if get_args.len() > 1 {
2721 snippet_with_applicability(cx, get_args[1].span, "..", &mut applicability)
2723 return; // not linting on a .get().unwrap() chain or variant
2726 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2727 needs_ref = get_args_str.parse::<usize>().is_ok();
2729 } else if is_type_diagnostic_item(cx, expr_ty, sym::vec_type) {
2730 needs_ref = get_args_str.parse::<usize>().is_ok();
2732 } else if is_type_diagnostic_item(cx, expr_ty, sym!(vecdeque_type)) {
2733 needs_ref = get_args_str.parse::<usize>().is_ok();
2735 } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym!(hashmap_type)) {
2738 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2742 return; // caller is not a type that we want to lint
2745 let mut span = expr.span;
2747 // Handle the case where the result is immediately dereferenced
2748 // by not requiring ref and pulling the dereference into the
2752 if let Some(parent) = get_parent_expr(cx, expr);
2753 if let hir::ExprKind::Unary(hir::UnOp::Deref, _) = parent.kind;
2760 let mut_str = if is_mut { "_mut" } else { "" };
2761 let borrow_str = if !needs_ref {
2774 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2775 mut_str, caller_type
2781 snippet_with_applicability(cx, get_args[0].span, "..", &mut applicability),
2788 fn lint_iter_skip_next(cx: &LateContext<'_>, expr: &hir::Expr<'_>, skip_args: &[hir::Expr<'_>]) {
2789 // lint if caller of skip is an Iterator
2790 if match_trait_method(cx, expr, &paths::ITERATOR) {
2791 if let [caller, n] = skip_args {
2792 let hint = format!(".nth({})", snippet(cx, n.span, ".."));
2796 expr.span.trim_start(caller.span).unwrap(),
2797 "called `skip(..).next()` on an iterator",
2798 "use `nth` instead",
2800 Applicability::MachineApplicable,
2806 pub(crate) fn derefs_to_slice<'tcx>(
2807 cx: &LateContext<'tcx>,
2808 expr: &'tcx hir::Expr<'tcx>,
2810 ) -> Option<&'tcx hir::Expr<'tcx>> {
2811 fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
2813 ty::Slice(_) => true,
2814 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2815 ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type),
2816 ty::Array(_, size) => size
2817 .try_eval_usize(cx.tcx, cx.param_env)
2818 .map_or(false, |size| size < 32),
2819 ty::Ref(_, inner, _) => may_slice(cx, inner),
2824 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
2825 if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
2832 ty::Slice(_) => Some(expr),
2833 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2834 ty::Ref(_, inner, _) => {
2835 if may_slice(cx, inner) {
2846 /// lint use of `unwrap()` for `Option`s and `Result`s
2847 fn lint_unwrap(cx: &LateContext<'_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2848 let obj_ty = cx.typeck_results().expr_ty(&unwrap_args[0]).peel_refs();
2850 let mess = if is_type_diagnostic_item(cx, obj_ty, sym::option_type) {
2851 Some((UNWRAP_USED, "an Option", "None"))
2852 } else if is_type_diagnostic_item(cx, obj_ty, sym::result_type) {
2853 Some((UNWRAP_USED, "a Result", "Err"))
2858 if let Some((lint, kind, none_value)) = mess {
2863 &format!("used `unwrap()` on `{}` value", kind,),
2866 "if you don't want to handle the `{}` case gracefully, consider \
2867 using `expect()` to provide a better panic message",
2874 /// lint use of `expect()` for `Option`s and `Result`s
2875 fn lint_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2876 let obj_ty = cx.typeck_results().expr_ty(&expect_args[0]).peel_refs();
2878 let mess = if is_type_diagnostic_item(cx, obj_ty, sym::option_type) {
2879 Some((EXPECT_USED, "an Option", "None"))
2880 } else if is_type_diagnostic_item(cx, obj_ty, sym::result_type) {
2881 Some((EXPECT_USED, "a Result", "Err"))
2886 if let Some((lint, kind, none_value)) = mess {
2891 &format!("used `expect()` on `{}` value", kind,),
2893 &format!("if this value is an `{}`, it will panic", none_value,),
2898 /// lint use of `ok().expect()` for `Result`s
2899 fn lint_ok_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2901 // lint if the caller of `ok()` is a `Result`
2902 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&ok_args[0]), sym::result_type);
2903 let result_type = cx.typeck_results().expr_ty(&ok_args[0]);
2904 if let Some(error_type) = get_error_type(cx, result_type);
2905 if has_debug_impl(error_type, cx);
2912 "called `ok().expect()` on a `Result` value",
2914 "you can call `expect()` directly on the `Result`",
2920 /// lint use of `map().flatten()` for `Iterators` and 'Options'
2921 fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2922 // lint if caller of `.map().flatten()` is an Iterator
2923 if match_trait_method(cx, expr, &paths::ITERATOR) {
2924 let map_closure_ty = cx.typeck_results().expr_ty(&map_args[1]);
2925 let is_map_to_option = match map_closure_ty.kind() {
2926 ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => {
2927 let map_closure_sig = match map_closure_ty.kind() {
2928 ty::Closure(_, substs) => substs.as_closure().sig(),
2929 _ => map_closure_ty.fn_sig(cx.tcx),
2931 let map_closure_return_ty = cx.tcx.erase_late_bound_regions(map_closure_sig.output());
2932 is_type_diagnostic_item(cx, map_closure_return_ty, sym::option_type)
2937 let method_to_use = if is_map_to_option {
2938 // `(...).map(...)` has type `impl Iterator<Item=Option<...>>
2941 // `(...).map(...)` has type `impl Iterator<Item=impl Iterator<...>>
2944 let func_snippet = snippet(cx, map_args[1].span, "..");
2945 let hint = format!(".{0}({1})", method_to_use, func_snippet);
2949 expr.span.with_lo(map_args[0].span.hi()),
2950 "called `map(..).flatten()` on an `Iterator`",
2951 &format!("try using `{}` instead", method_to_use),
2953 Applicability::MachineApplicable,
2957 // lint if caller of `.map().flatten()` is an Option
2958 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type) {
2959 let func_snippet = snippet(cx, map_args[1].span, "..");
2960 let hint = format!(".and_then({})", func_snippet);
2964 expr.span.with_lo(map_args[0].span.hi()),
2965 "called `map(..).flatten()` on an `Option`",
2966 "try using `and_then` instead",
2968 Applicability::MachineApplicable,
2973 const MAP_UNWRAP_OR_MSRV: RustcVersion = RustcVersion::new(1, 41, 0);
2975 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2976 /// Return true if lint triggered
2977 fn lint_map_unwrap_or_else<'tcx>(
2978 cx: &LateContext<'tcx>,
2979 expr: &'tcx hir::Expr<'_>,
2980 map_args: &'tcx [hir::Expr<'_>],
2981 unwrap_args: &'tcx [hir::Expr<'_>],
2982 msrv: Option<&RustcVersion>,
2984 if !meets_msrv(msrv, &MAP_UNWRAP_OR_MSRV) {
2987 // lint if the caller of `map()` is an `Option`
2988 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::option_type);
2989 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym::result_type);
2991 if is_option || is_result {
2992 // Don't make a suggestion that may fail to compile due to mutably borrowing
2993 // the same variable twice.
2994 let map_mutated_vars = mutated_variables(&map_args[0], cx);
2995 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2996 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2997 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
3005 let msg = if is_option {
3006 "called `map(<f>).unwrap_or_else(<g>)` on an `Option` value. This can be done more directly by calling \
3007 `map_or_else(<g>, <f>)` instead"
3009 "called `map(<f>).unwrap_or_else(<g>)` on a `Result` value. This can be done more directly by calling \
3010 `.map_or_else(<g>, <f>)` instead"
3012 // get snippets for args to map() and unwrap_or_else()
3013 let map_snippet = snippet(cx, map_args[1].span, "..");
3014 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
3015 // lint, with note if neither arg is > 1 line and both map() and
3016 // unwrap_or_else() have the same span
3017 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
3018 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
3019 if same_span && !multiline {
3020 let var_snippet = snippet(cx, map_args[0].span, "..");
3027 format!("{}.map_or_else({}, {})", var_snippet, unwrap_snippet, map_snippet),
3028 Applicability::MachineApplicable,
3031 } else if same_span && multiline {
3032 span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
3040 /// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
3041 fn lint_map_or_none<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>]) {
3042 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym::option_type);
3043 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym::result_type);
3045 // There are two variants of this `map_or` lint:
3046 // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
3047 // (2) using `map_or` as a combinator instead of `and_then`
3049 // (For this lint) we don't care if any other type calls `map_or`
3050 if !is_option && !is_result {
3054 let (lint_name, msg, instead, hint) = {
3055 let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
3056 match_qpath(qpath, &paths::OPTION_NONE)
3061 if !default_arg_is_none {
3066 let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
3067 match_qpath(qpath, &paths::OPTION_SOME)
3073 let self_snippet = snippet(cx, map_or_args[0].span, "..");
3074 let func_snippet = snippet(cx, map_or_args[2].span, "..");
3075 let msg = "called `map_or(None, ..)` on an `Option` value. This can be done more directly by calling \
3076 `and_then(..)` instead";
3080 "try using `and_then` instead",
3081 format!("{0}.and_then({1})", self_snippet, func_snippet),
3083 } else if f_arg_is_some {
3084 let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
3086 let self_snippet = snippet(cx, map_or_args[0].span, "..");
3088 RESULT_MAP_OR_INTO_OPTION,
3090 "try using `ok` instead",
3091 format!("{0}.ok()", self_snippet),
3106 Applicability::MachineApplicable,
3110 /// lint use of `filter().next()` for `Iterators`
3111 fn lint_filter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
3112 // lint if caller of `.filter().next()` is an Iterator
3113 if match_trait_method(cx, expr, &paths::ITERATOR) {
3114 let msg = "called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
3115 `.find(..)` instead.";
3116 let filter_snippet = snippet(cx, filter_args[1].span, "..");
3117 if filter_snippet.lines().count() <= 1 {
3118 let iter_snippet = snippet(cx, filter_args[0].span, "..");
3119 // add note if not multi-line
3126 format!("{}.find({})", iter_snippet, filter_snippet),
3127 Applicability::MachineApplicable,
3130 span_lint(cx, FILTER_NEXT, expr.span, msg);
3135 /// lint use of `skip_while().next()` for `Iterators`
3136 fn lint_skip_while_next<'tcx>(
3137 cx: &LateContext<'tcx>,
3138 expr: &'tcx hir::Expr<'_>,
3139 _skip_while_args: &'tcx [hir::Expr<'_>],
3141 // lint if caller of `.skip_while().next()` is an Iterator
3142 if match_trait_method(cx, expr, &paths::ITERATOR) {
3147 "called `skip_while(<p>).next()` on an `Iterator`",
3149 "this is more succinctly expressed by calling `.find(!<p>)` instead",
3154 /// lint use of `filter().map()` or `find().map()` for `Iterators`
3155 fn lint_filter_map<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, is_find: bool) {
3157 if let ExprKind::MethodCall(_, _, [map_recv, map_arg], map_span) = expr.kind;
3158 if let ExprKind::MethodCall(_, _, [_, filter_arg], filter_span) = map_recv.kind;
3159 if match_trait_method(cx, map_recv, &paths::ITERATOR);
3161 // filter(|x| ...is_some())...
3162 if let ExprKind::Closure(_, _, filter_body_id, ..) = filter_arg.kind;
3163 let filter_body = cx.tcx.hir().body(filter_body_id);
3164 if let [filter_param] = filter_body.params;
3165 // optional ref pattern: `filter(|&x| ..)`
3166 let (filter_pat, is_filter_param_ref) = if let PatKind::Ref(ref_pat, _) = filter_param.pat.kind {
3169 (filter_param.pat, false)
3171 // closure ends with is_some() or is_ok()
3172 if let PatKind::Binding(_, filter_param_id, _, None) = filter_pat.kind;
3173 if let ExprKind::MethodCall(path, _, [filter_arg], _) = filter_body.value.kind;
3174 if let Some(opt_ty) = cx.typeck_results().expr_ty(filter_arg).ty_adt_def();
3175 if let Some(is_result) = if cx.tcx.is_diagnostic_item(sym::option_type, opt_ty.did) {
3177 } else if cx.tcx.is_diagnostic_item(sym::result_type, opt_ty.did) {
3182 if path.ident.name.as_str() == if is_result { "is_ok" } else { "is_some" };
3184 // ...map(|x| ...unwrap())
3185 if let ExprKind::Closure(_, _, map_body_id, ..) = map_arg.kind;
3186 let map_body = cx.tcx.hir().body(map_body_id);
3187 if let [map_param] = map_body.params;
3188 if let PatKind::Binding(_, map_param_id, map_param_ident, None) = map_param.pat.kind;
3189 // closure ends with expect() or unwrap()
3190 if let ExprKind::MethodCall(seg, _, [map_arg, ..], _) = map_body.value.kind;
3191 if matches!(seg.ident.name, sym::expect | sym::unwrap | sym::unwrap_or);
3193 let eq_fallback = |a: &Expr<'_>, b: &Expr<'_>| {
3194 // in `filter(|x| ..)`, replace `*x` with `x`
3195 let a_path = if_chain! {
3196 if !is_filter_param_ref;
3197 if let ExprKind::Unary(UnOp::Deref, expr_path) = a.kind;
3198 then { expr_path } else { a }
3200 // let the filter closure arg and the map closure arg be equal
3202 if path_to_local_id(a_path, filter_param_id);
3203 if path_to_local_id(b, map_param_id);
3204 if TyS::same_type(cx.typeck_results().expr_ty_adjusted(a), cx.typeck_results().expr_ty_adjusted(b));
3211 if SpanlessEq::new(cx).expr_fallback(eq_fallback).eq_expr(filter_arg, map_arg);
3213 let span = filter_span.to(map_span);
3214 let (filter_name, lint) = if is_find {
3215 ("find", MANUAL_FIND_MAP)
3217 ("filter", MANUAL_FILTER_MAP)
3219 let msg = format!("`{}(..).map(..)` can be simplified as `{0}_map(..)`", filter_name);
3220 let to_opt = if is_result { ".ok()" } else { "" };
3221 let sugg = format!("{}_map(|{}| {}{})", filter_name, map_param_ident,
3222 snippet(cx, map_arg.span, ".."), to_opt);
3223 span_lint_and_sugg(cx, lint, span, &msg, "try", sugg, Applicability::MachineApplicable);
3228 const FILTER_MAP_NEXT_MSRV: RustcVersion = RustcVersion::new(1, 30, 0);
3230 /// lint use of `filter_map().next()` for `Iterators`
3231 fn lint_filter_map_next<'tcx>(
3232 cx: &LateContext<'tcx>,
3233 expr: &'tcx hir::Expr<'_>,
3234 filter_args: &'tcx [hir::Expr<'_>],
3235 msrv: Option<&RustcVersion>,
3237 if match_trait_method(cx, expr, &paths::ITERATOR) {
3238 if !meets_msrv(msrv, &FILTER_MAP_NEXT_MSRV) {
3242 let msg = "called `filter_map(..).next()` on an `Iterator`. This is more succinctly expressed by calling \
3243 `.find_map(..)` instead.";
3244 let filter_snippet = snippet(cx, filter_args[1].span, "..");
3245 if filter_snippet.lines().count() <= 1 {
3246 let iter_snippet = snippet(cx, filter_args[0].span, "..");
3253 format!("{}.find_map({})", iter_snippet, filter_snippet),
3254 Applicability::MachineApplicable,
3257 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
3262 /// lint use of `filter_map().map()` for `Iterators`
3263 fn lint_filter_map_map<'tcx>(
3264 cx: &LateContext<'tcx>,
3265 expr: &'tcx hir::Expr<'_>,
3266 _filter_args: &'tcx [hir::Expr<'_>],
3267 _map_args: &'tcx [hir::Expr<'_>],
3269 // lint if caller of `.filter_map().map()` is an Iterator
3270 if match_trait_method(cx, expr, &paths::ITERATOR) {
3271 let msg = "called `filter_map(..).map(..)` on an `Iterator`";
3272 let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
3273 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3277 /// lint use of `filter().flat_map()` for `Iterators`
3278 fn lint_filter_flat_map<'tcx>(
3279 cx: &LateContext<'tcx>,
3280 expr: &'tcx hir::Expr<'_>,
3281 _filter_args: &'tcx [hir::Expr<'_>],
3282 _map_args: &'tcx [hir::Expr<'_>],
3284 // lint if caller of `.filter().flat_map()` is an Iterator
3285 if match_trait_method(cx, expr, &paths::ITERATOR) {
3286 let msg = "called `filter(..).flat_map(..)` on an `Iterator`";
3287 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
3288 and filtering by returning `iter::empty()`";
3289 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3293 /// lint use of `filter_map().flat_map()` for `Iterators`
3294 fn lint_filter_map_flat_map<'tcx>(
3295 cx: &LateContext<'tcx>,
3296 expr: &'tcx hir::Expr<'_>,
3297 _filter_args: &'tcx [hir::Expr<'_>],
3298 _map_args: &'tcx [hir::Expr<'_>],
3300 // lint if caller of `.filter_map().flat_map()` is an Iterator
3301 if match_trait_method(cx, expr, &paths::ITERATOR) {
3302 let msg = "called `filter_map(..).flat_map(..)` on an `Iterator`";
3303 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
3304 and filtering by returning `iter::empty()`";
3305 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
3309 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
3310 fn lint_flat_map_identity<'tcx>(
3311 cx: &LateContext<'tcx>,
3312 expr: &'tcx hir::Expr<'_>,
3313 flat_map_args: &'tcx [hir::Expr<'_>],
3314 flat_map_span: Span,
3316 if match_trait_method(cx, expr, &paths::ITERATOR) {
3317 let arg_node = &flat_map_args[1].kind;
3319 let apply_lint = |message: &str| {
3323 flat_map_span.with_hi(expr.span.hi()),
3326 "flatten()".to_string(),
3327 Applicability::MachineApplicable,
3332 if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
3333 let body = cx.tcx.hir().body(*body_id);
3335 if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
3336 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
3338 if path.segments.len() == 1;
3339 if path.segments[0].ident.name == binding_ident.name;
3342 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
3347 if let hir::ExprKind::Path(ref qpath) = arg_node;
3349 if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
3352 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
3358 /// lint searching an Iterator followed by `is_some()`
3359 /// or calling `find()` on a string followed by `is_some()`
3360 fn lint_search_is_some<'tcx>(
3361 cx: &LateContext<'tcx>,
3362 expr: &'tcx hir::Expr<'_>,
3363 search_method: &str,
3364 search_args: &'tcx [hir::Expr<'_>],
3365 is_some_args: &'tcx [hir::Expr<'_>],
3368 // lint if caller of search is an Iterator
3369 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
3371 "called `is_some()` after searching an `Iterator` with `{}`",
3374 let hint = "this is more succinctly expressed by calling `any()`";
3375 let search_snippet = snippet(cx, search_args[1].span, "..");
3376 if search_snippet.lines().count() <= 1 {
3377 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
3378 // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
3379 let any_search_snippet = if_chain! {
3380 if search_method == "find";
3381 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
3382 let closure_body = cx.tcx.hir().body(body_id);
3383 if let Some(closure_arg) = closure_body.params.get(0);
3385 if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
3386 Some(search_snippet.replacen('&', "", 1))
3387 } else if let PatKind::Binding(_, _, ident, _) = strip_pat_refs(&closure_arg.pat).kind {
3388 let name = &*ident.name.as_str();
3389 Some(search_snippet.replace(&format!("*{}", name), name))
3397 // add note if not multi-line
3401 method_span.with_hi(expr.span.hi()),
3403 "use `any()` instead",
3406 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
3408 Applicability::MachineApplicable,
3411 span_lint_and_help(cx, SEARCH_IS_SOME, expr.span, &msg, None, hint);
3414 // lint if `find()` is called by `String` or `&str`
3415 else if search_method == "find" {
3416 let is_string_or_str_slice = |e| {
3417 let self_ty = cx.typeck_results().expr_ty(e).peel_refs();
3418 if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
3421 *self_ty.kind() == ty::Str
3425 if is_string_or_str_slice(&search_args[0]);
3426 if is_string_or_str_slice(&search_args[1]);
3428 let msg = "called `is_some()` after calling `find()` on a string";
3429 let mut applicability = Applicability::MachineApplicable;
3430 let find_arg = snippet_with_applicability(cx, search_args[1].span, "..", &mut applicability);
3434 method_span.with_hi(expr.span.hi()),
3436 "use `contains()` instead",
3437 format!("contains({})", find_arg),
3445 /// Used for `lint_binary_expr_with_method_call`.
3446 #[derive(Copy, Clone)]
3447 struct BinaryExprInfo<'a> {
3448 expr: &'a hir::Expr<'a>,
3449 chain: &'a hir::Expr<'a>,
3450 other: &'a hir::Expr<'a>,
3454 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3455 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3456 macro_rules! lint_with_both_lhs_and_rhs {
3457 ($func:ident, $cx:expr, $info:ident) => {
3458 if !$func($cx, $info) {
3459 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3460 if $func($cx, $info) {
3467 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
3468 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
3469 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
3470 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
3473 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3475 cx: &LateContext<'_>,
3476 info: &BinaryExprInfo<'_>,
3477 chain_methods: &[&str],
3478 lint: &'static Lint,
3482 if let Some(args) = method_chain_args(info.chain, chain_methods);
3483 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
3484 if arg_char.len() == 1;
3485 if let hir::ExprKind::Path(ref qpath) = fun.kind;
3486 if let Some(segment) = single_segment_path(qpath);
3487 if segment.ident.name == sym::Some;
3489 let mut applicability = Applicability::MachineApplicable;
3490 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0][0]).peel_refs();
3492 if *self_ty.kind() != ty::Str {
3500 &format!("you should use the `{}` method", suggest),
3502 format!("{}{}.{}({})",
3503 if info.eq { "" } else { "!" },
3504 snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3506 snippet_with_applicability(cx, arg_char[0].span, "..", &mut applicability)),
3517 /// Checks for the `CHARS_NEXT_CMP` lint.
3518 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3519 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
3522 /// Checks for the `CHARS_LAST_CMP` lint.
3523 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3524 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
3527 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
3531 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
3532 fn lint_chars_cmp_with_unwrap<'tcx>(
3533 cx: &LateContext<'tcx>,
3534 info: &BinaryExprInfo<'_>,
3535 chain_methods: &[&str],
3536 lint: &'static Lint,
3540 if let Some(args) = method_chain_args(info.chain, chain_methods);
3541 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
3542 if let ast::LitKind::Char(c) = lit.node;
3544 let mut applicability = Applicability::MachineApplicable;
3549 &format!("you should use the `{}` method", suggest),
3551 format!("{}{}.{}('{}')",
3552 if info.eq { "" } else { "!" },
3553 snippet_with_applicability(cx, args[0][0].span, "..", &mut applicability),
3566 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
3567 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3568 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3571 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3572 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3573 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3576 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3580 fn get_hint_if_single_char_arg(
3581 cx: &LateContext<'_>,
3582 arg: &hir::Expr<'_>,
3583 applicability: &mut Applicability,
3584 ) -> Option<String> {
3586 if let hir::ExprKind::Lit(lit) = &arg.kind;
3587 if let ast::LitKind::Str(r, style) = lit.node;
3588 let string = r.as_str();
3589 if string.chars().count() == 1;
3591 let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
3592 let ch = if let ast::StrStyle::Raw(nhash) = style {
3593 let nhash = nhash as usize;
3594 // for raw string: r##"a"##
3595 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3597 // for regular string: "a"
3598 &snip[1..(snip.len() - 1)]
3600 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3608 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3609 fn lint_single_char_pattern(cx: &LateContext<'_>, _expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
3610 let mut applicability = Applicability::MachineApplicable;
3611 if let Some(hint) = get_hint_if_single_char_arg(cx, arg, &mut applicability) {
3614 SINGLE_CHAR_PATTERN,
3616 "single-character string constant used as pattern",
3617 "try using a `char` instead",
3624 /// lint for length-1 `str`s as argument for `push_str`
3625 fn lint_single_char_push_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3626 let mut applicability = Applicability::MachineApplicable;
3627 if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[1], &mut applicability) {
3628 let base_string_snippet =
3629 snippet_with_applicability(cx, args[0].span.source_callsite(), "..", &mut applicability);
3630 let sugg = format!("{}.push({})", base_string_snippet, extension_string);
3633 SINGLE_CHAR_ADD_STR,
3635 "calling `push_str()` using a single-character string literal",
3636 "consider using `push` with a character literal",
3643 /// lint for length-1 `str`s as argument for `insert_str`
3644 fn lint_single_char_insert_string(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3645 let mut applicability = Applicability::MachineApplicable;
3646 if let Some(extension_string) = get_hint_if_single_char_arg(cx, &args[2], &mut applicability) {
3647 let base_string_snippet =
3648 snippet_with_applicability(cx, args[0].span.source_callsite(), "_", &mut applicability);
3649 let pos_arg = snippet_with_applicability(cx, args[1].span, "..", &mut applicability);
3650 let sugg = format!("{}.insert({}, {})", base_string_snippet, pos_arg, extension_string);
3653 SINGLE_CHAR_ADD_STR,
3655 "calling `insert_str()` using a single-character string literal",
3656 "consider using `insert` with a character literal",
3663 /// Checks for the `USELESS_ASREF` lint.
3664 fn lint_asref(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3665 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3666 // check if the call is to the actual `AsRef` or `AsMut` trait
3667 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3668 // check if the type after `as_ref` or `as_mut` is the same as before
3669 let recvr = &as_ref_args[0];
3670 let rcv_ty = cx.typeck_results().expr_ty(recvr);
3671 let res_ty = cx.typeck_results().expr_ty(expr);
3672 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3673 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3674 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3675 // allow the `as_ref` or `as_mut` if it is followed by another method call
3677 if let Some(parent) = get_parent_expr(cx, expr);
3678 if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind;
3679 if span != &expr.span;
3685 let mut applicability = Applicability::MachineApplicable;
3690 &format!("this call to `{}` does nothing", call_name),
3692 snippet_with_applicability(cx, recvr.span, "..", &mut applicability).to_string(),
3699 fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3700 has_iter_method(cx, self_ref_ty).map(|ty_name| {
3701 let mutbl = match self_ref_ty.kind() {
3702 ty::Ref(_, _, mutbl) => mutbl,
3703 _ => unreachable!(),
3705 let method_name = match mutbl {
3706 hir::Mutability::Not => "iter",
3707 hir::Mutability::Mut => "iter_mut",
3709 (ty_name, method_name)
3713 fn lint_into_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3714 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3717 if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3723 "this `.into_iter()` call is equivalent to `.{}()` and will not consume the `{}`",
3727 method_name.to_string(),
3728 Applicability::MachineApplicable,
3733 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3734 fn lint_maybe_uninit(cx: &LateContext<'_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3736 if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3738 if let hir::ExprKind::Path(ref path) = callee.kind;
3739 if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3740 if !is_maybe_uninit_ty_valid(cx, cx.typeck_results().expr_ty_adjusted(outer));
3744 UNINIT_ASSUMED_INIT,
3746 "this call for this type may be undefined behavior"
3752 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
3754 ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3755 ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3756 ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
3761 fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
3766 "this call to `map()` won't have an effect on the call to `count()`",
3768 "make sure you did not confuse `map` with `filter` or `for_each`",
3772 const OPTION_AS_REF_DEREF_MSRV: RustcVersion = RustcVersion::new(1, 40, 0);
3774 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3775 fn lint_option_as_ref_deref<'tcx>(
3776 cx: &LateContext<'tcx>,
3777 expr: &hir::Expr<'_>,
3778 as_ref_args: &[hir::Expr<'_>],
3779 map_args: &[hir::Expr<'_>],
3781 msrv: Option<&RustcVersion>,
3783 if !meets_msrv(msrv, &OPTION_AS_REF_DEREF_MSRV) {
3787 let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
3789 let option_ty = cx.typeck_results().expr_ty(&as_ref_args[0]);
3790 if !is_type_diagnostic_item(cx, option_ty, sym::option_type) {
3794 let deref_aliases: [&[&str]; 9] = [
3795 &paths::DEREF_TRAIT_METHOD,
3796 &paths::DEREF_MUT_TRAIT_METHOD,
3797 &paths::CSTRING_AS_C_STR,
3798 &paths::OS_STRING_AS_OS_STR,
3799 &paths::PATH_BUF_AS_PATH,
3800 &paths::STRING_AS_STR,
3801 &paths::STRING_AS_MUT_STR,
3802 &paths::VEC_AS_SLICE,
3803 &paths::VEC_AS_MUT_SLICE,
3806 let is_deref = match map_args[1].kind {
3807 hir::ExprKind::Path(ref expr_qpath) => cx
3808 .qpath_res(expr_qpath, map_args[1].hir_id)
3810 .map_or(false, |fun_def_id| {
3811 deref_aliases.iter().any(|path| match_def_path(cx, fun_def_id, path))
3813 hir::ExprKind::Closure(_, _, body_id, _, _) => {
3814 let closure_body = cx.tcx.hir().body(body_id);
3815 let closure_expr = remove_blocks(&closure_body.value);
3817 match &closure_expr.kind {
3818 hir::ExprKind::MethodCall(_, _, args, _) => {
3821 if path_to_local_id(&args[0], closure_body.params[0].pat.hir_id);
3824 .expr_adjustments(&args[0])
3827 .collect::<Box<[_]>>();
3828 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3830 let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
3831 deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3837 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
3839 if let hir::ExprKind::Unary(hir::UnOp::Deref, ref inner1) = inner.kind;
3840 if let hir::ExprKind::Unary(hir::UnOp::Deref, ref inner2) = inner1.kind;
3842 path_to_local_id(inner2, closure_body.params[0].pat.hir_id)
3855 let current_method = if is_mut {
3856 format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
3858 format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
3860 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3861 let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3862 let suggestion = format!("try using {} instead", method_hint);
3865 "called `{0}` on an Option value. This can be done more directly \
3866 by calling `{1}` instead",
3867 current_method, hint
3871 OPTION_AS_REF_DEREF,
3876 Applicability::MachineApplicable,
3881 fn lint_map_collect(
3882 cx: &LateContext<'_>,
3883 expr: &hir::Expr<'_>,
3884 map_args: &[hir::Expr<'_>],
3885 collect_args: &[hir::Expr<'_>],
3888 // called on Iterator
3889 if let [map_expr] = collect_args;
3890 if match_trait_method(cx, map_expr, &paths::ITERATOR);
3891 // return of collect `Result<(),_>`
3892 let collect_ret_ty = cx.typeck_results().expr_ty(expr);
3893 if is_type_diagnostic_item(cx, collect_ret_ty, sym::result_type);
3894 if let ty::Adt(_, substs) = collect_ret_ty.kind();
3895 if let Some(result_t) = substs.types().next();
3896 if result_t.is_unit();
3897 // get parts for snippet
3898 if let [iter, map_fn] = map_args;
3902 MAP_COLLECT_RESULT_UNIT,
3904 "`.map().collect()` can be replaced with `.try_for_each()`",
3907 "{}.try_for_each({})",
3908 snippet(cx, iter.span, ".."),
3909 snippet(cx, map_fn.span, "..")
3911 Applicability::MachineApplicable,
3917 /// Given a `Result<T, E>` type, return its error type (`E`).
3918 fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3920 ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym::result_type) => substs.types().nth(1),
3925 /// This checks whether a given type is known to implement Debug.
3926 fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
3928 .get_diagnostic_item(sym::debug_trait)
3929 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3934 StartsWith(&'static str),
3938 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3939 (Convention::Eq("new"), &[SelfKind::No]),
3940 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3941 (Convention::StartsWith("from_"), &[SelfKind::No]),
3942 (Convention::StartsWith("into_"), &[SelfKind::Value]),
3943 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3944 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3945 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3948 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3949 unsafety: hir::Unsafety::Normal,
3950 constness: hir::Constness::NotConst,
3951 asyncness: hir::IsAsync::NotAsync,
3952 abi: rustc_target::spec::abi::Abi::Rust,
3955 struct ShouldImplTraitCase {
3956 trait_name: &'static str,
3957 method_name: &'static str,
3959 fn_header: hir::FnHeader,
3960 // implicit self kind expected (none, self, &self, ...)
3961 self_kind: SelfKind,
3962 // checks against the output type
3963 output_type: OutType,
3964 // certain methods with explicit lifetimes can't implement the equivalent trait method
3965 lint_explicit_lifetime: bool,
3967 impl ShouldImplTraitCase {
3969 trait_name: &'static str,
3970 method_name: &'static str,
3972 fn_header: hir::FnHeader,
3973 self_kind: SelfKind,
3974 output_type: OutType,
3975 lint_explicit_lifetime: bool,
3976 ) -> ShouldImplTraitCase {
3977 ShouldImplTraitCase {
3984 lint_explicit_lifetime,
3988 fn lifetime_param_cond(&self, impl_item: &hir::ImplItem<'_>) -> bool {
3989 self.lint_explicit_lifetime
3990 || !impl_item.generics.params.iter().any(|p| {
3993 hir::GenericParamKind::Lifetime {
3994 kind: hir::LifetimeParamKind::Explicit
4002 const TRAIT_METHODS: [ShouldImplTraitCase; 30] = [
4003 ShouldImplTraitCase::new("std::ops::Add", "add", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4004 ShouldImplTraitCase::new("std::convert::AsMut", "as_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
4005 ShouldImplTraitCase::new("std::convert::AsRef", "as_ref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
4006 ShouldImplTraitCase::new("std::ops::BitAnd", "bitand", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4007 ShouldImplTraitCase::new("std::ops::BitOr", "bitor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4008 ShouldImplTraitCase::new("std::ops::BitXor", "bitxor", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4009 ShouldImplTraitCase::new("std::borrow::Borrow", "borrow", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
4010 ShouldImplTraitCase::new("std::borrow::BorrowMut", "borrow_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
4011 ShouldImplTraitCase::new("std::clone::Clone", "clone", 1, FN_HEADER, SelfKind::Ref, OutType::Any, true),
4012 ShouldImplTraitCase::new("std::cmp::Ord", "cmp", 2, FN_HEADER, SelfKind::Ref, OutType::Any, true),
4013 // FIXME: default doesn't work
4014 ShouldImplTraitCase::new("std::default::Default", "default", 0, FN_HEADER, SelfKind::No, OutType::Any, true),
4015 ShouldImplTraitCase::new("std::ops::Deref", "deref", 1, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
4016 ShouldImplTraitCase::new("std::ops::DerefMut", "deref_mut", 1, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
4017 ShouldImplTraitCase::new("std::ops::Div", "div", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4018 ShouldImplTraitCase::new("std::ops::Drop", "drop", 1, FN_HEADER, SelfKind::RefMut, OutType::Unit, true),
4019 ShouldImplTraitCase::new("std::cmp::PartialEq", "eq", 2, FN_HEADER, SelfKind::Ref, OutType::Bool, true),
4020 ShouldImplTraitCase::new("std::iter::FromIterator", "from_iter", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
4021 ShouldImplTraitCase::new("std::str::FromStr", "from_str", 1, FN_HEADER, SelfKind::No, OutType::Any, true),
4022 ShouldImplTraitCase::new("std::hash::Hash", "hash", 2, FN_HEADER, SelfKind::Ref, OutType::Unit, true),
4023 ShouldImplTraitCase::new("std::ops::Index", "index", 2, FN_HEADER, SelfKind::Ref, OutType::Ref, true),
4024 ShouldImplTraitCase::new("std::ops::IndexMut", "index_mut", 2, FN_HEADER, SelfKind::RefMut, OutType::Ref, true),
4025 ShouldImplTraitCase::new("std::iter::IntoIterator", "into_iter", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
4026 ShouldImplTraitCase::new("std::ops::Mul", "mul", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4027 ShouldImplTraitCase::new("std::ops::Neg", "neg", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
4028 ShouldImplTraitCase::new("std::iter::Iterator", "next", 1, FN_HEADER, SelfKind::RefMut, OutType::Any, false),
4029 ShouldImplTraitCase::new("std::ops::Not", "not", 1, FN_HEADER, SelfKind::Value, OutType::Any, true),
4030 ShouldImplTraitCase::new("std::ops::Rem", "rem", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4031 ShouldImplTraitCase::new("std::ops::Shl", "shl", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4032 ShouldImplTraitCase::new("std::ops::Shr", "shr", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4033 ShouldImplTraitCase::new("std::ops::Sub", "sub", 2, FN_HEADER, SelfKind::Value, OutType::Any, true),
4037 const PATTERN_METHODS: [(&str, usize); 17] = [
4045 ("split_terminator", 1),
4046 ("rsplit_terminator", 1),
4051 ("match_indices", 1),
4052 ("rmatch_indices", 1),
4053 ("trim_start_matches", 1),
4054 ("trim_end_matches", 1),
4057 #[derive(Clone, Copy, PartialEq, Debug)]
4066 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
4067 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
4068 if ty == parent_ty {
4070 } else if ty.is_box() {
4071 ty.boxed_ty() == parent_ty
4072 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
4073 if let ty::Adt(_, substs) = ty.kind() {
4074 substs.types().next().map_or(false, |t| t == parent_ty)
4083 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
4084 if let ty::Ref(_, t, m) = *ty.kind() {
4085 return m == mutability && t == parent_ty;
4088 let trait_path = match mutability {
4089 hir::Mutability::Not => &paths::ASREF_TRAIT,
4090 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
4093 let trait_def_id = match get_trait_def_id(cx, trait_path) {
4095 None => return false,
4097 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
4101 Self::Value => matches_value(cx, parent_ty, ty),
4102 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
4103 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
4104 Self::No => ty != parent_ty,
4109 fn description(self) -> &'static str {
4111 Self::Value => "self by value",
4112 Self::Ref => "self by reference",
4113 Self::RefMut => "self by mutable reference",
4114 Self::No => "no self",
4121 fn check(&self, other: &str) -> bool {
4123 Self::Eq(this) => this == other,
4124 Self::StartsWith(this) => other.starts_with(this) && this != other,
4129 impl fmt::Display for Convention {
4130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
4132 Self::Eq(this) => this.fmt(f),
4133 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
4138 #[derive(Clone, Copy)]
4147 fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
4148 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
4150 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
4151 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
4152 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
4153 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
4154 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
4160 fn is_bool(ty: &hir::Ty<'_>) -> bool {
4161 if let hir::TyKind::Path(ref p) = ty.kind {
4162 match_qpath(p, &["bool"])
4168 fn check_pointer_offset(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4171 if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.typeck_results().expr_ty(&args[0]).kind();
4172 if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
4175 span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
4180 fn lint_filetype_is_file(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4181 let ty = cx.typeck_results().expr_ty(&args[0]);
4183 if !match_type(cx, ty, &paths::FILE_TYPE) {
4189 let lint_unary: &str;
4190 let help_unary: &str;
4192 if let Some(parent) = get_parent_expr(cx, expr);
4193 if let hir::ExprKind::Unary(op, _) = parent.kind;
4194 if op == hir::UnOp::Not;
4207 let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
4208 let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
4209 span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
4212 fn lint_from_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
4213 let ty = cx.typeck_results().expr_ty(expr);
4214 let arg_ty = cx.typeck_results().expr_ty(&args[0]);
4217 if let Some(from_iter_id) = get_trait_def_id(cx, &paths::FROM_ITERATOR);
4218 if let Some(iter_id) = get_trait_def_id(cx, &paths::ITERATOR);
4220 if implements_trait(cx, ty, from_iter_id, &[]) && implements_trait(cx, arg_ty, iter_id, &[]);
4222 // `expr` implements `FromIterator` trait
4223 let iter_expr = sugg::Sugg::hir(cx, &args[0], "..").maybe_par();
4224 let turbofish = extract_turbofish(cx, expr, ty);
4225 let sugg = format!("{}.collect::<{}>()", iter_expr, turbofish);
4228 FROM_ITER_INSTEAD_OF_COLLECT,
4230 "usage of `FromIterator::from_iter`",
4231 "use `.collect()` instead of `::from_iter()`",
4233 Applicability::MaybeIncorrect,
4239 fn extract_turbofish(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ty: Ty<'tcx>) -> String {
4241 let call_site = expr.span.source_callsite();
4242 if let Ok(snippet) = cx.sess().source_map().span_to_snippet(call_site);
4243 let snippet_split = snippet.split("::").collect::<Vec<_>>();
4244 if let Some((_, elements)) = snippet_split.split_last();
4247 // is there a type specifier? (i.e.: like `<u32>` in `collections::BTreeSet::<u32>::`)
4248 if let Some(type_specifier) = snippet_split.iter().find(|e| e.starts_with('<') && e.ends_with('>')) {
4249 // remove the type specifier from the path elements
4250 let without_ts = elements.iter().filter_map(|e| {
4251 if e == type_specifier { None } else { Some((*e).to_string()) }
4252 }).collect::<Vec<_>>();
4253 // join and add the type specifier at the end (i.e.: `collections::BTreeSet<u32>`)
4254 format!("{}{}", without_ts.join("::"), type_specifier)
4256 // type is not explicitly specified so wildcards are needed
4257 // i.e.: 2 wildcards in `std::collections::BTreeMap<&i32, &char>`
4258 let ty_str = ty.to_string();
4259 let start = ty_str.find('<').unwrap_or(0);
4260 let end = ty_str.find('>').unwrap_or_else(|| ty_str.len());
4261 let nb_wildcard = ty_str[start..end].split(',').count();
4262 let wildcards = format!("_{}", ", _".repeat(nb_wildcard - 1));
4263 format!("{}<{}>", elements.join("::"), wildcards)
4271 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
4272 expected.constness == actual.constness
4273 && expected.unsafety == actual.unsafety
4274 && expected.asyncness == actual.asyncness