1 mod option_map_unwrap_or;
2 mod unnecessary_filter_map;
8 use if_chain::if_chain;
11 use rustc::hir::def::{DefKind, Res};
12 use rustc::hir::intravisit::{self, Visitor};
13 use rustc::lint::{in_external_macro, LateContext, LateLintPass, Lint, LintArray, LintContext, LintPass};
14 use rustc::ty::{self, Predicate, Ty};
15 use rustc::{declare_lint_pass, declare_tool_lint};
16 use rustc_errors::Applicability;
18 use syntax::source_map::{BytePos, Span};
19 use syntax::symbol::LocalInternedString;
21 use crate::utils::paths;
22 use crate::utils::sugg;
23 use crate::utils::usage::mutated_variables;
25 get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, implements_trait, in_macro, is_copy,
26 is_ctor_function, is_expn_of, is_self, is_self_ty, iter_input_pats, last_path_segment, match_def_path, match_path,
27 match_qpath, match_trait_method, match_type, match_var, method_calls, method_chain_args, remove_blocks, return_ty,
28 same_tys, single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite, span_lint,
29 span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
32 declare_clippy_lint! {
33 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
35 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
36 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
37 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
38 /// `Allow` by default.
40 /// **Known problems:** None.
46 pub OPTION_UNWRAP_USED,
48 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
51 declare_clippy_lint! {
52 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
54 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
55 /// values. Normally, you want to implement more sophisticated error handling,
56 /// and propagate errors upwards with `try!`.
58 /// Even if you want to panic on errors, not all `Error`s implement good
59 /// messages on display. Therefore, it may be beneficial to look at the places
60 /// where they may get displayed. Activate this lint to do just that.
62 /// **Known problems:** None.
68 pub RESULT_UNWRAP_USED,
70 "using `Result.unwrap()`, which might be better handled"
73 declare_clippy_lint! {
74 /// **What it does:** Checks for methods that should live in a trait
75 /// implementation of a `std` trait (see [llogiq's blog
76 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
77 /// information) instead of an inherent implementation.
79 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
80 /// the code, often with very little cost. Also people seeing a `mul(...)`
82 /// may expect `*` to work equally, so you should have good reason to disappoint
85 /// **Known problems:** None.
91 /// fn add(&self, other: &X) -> X {
96 pub SHOULD_IMPLEMENT_TRAIT,
98 "defining a method that should be implementing a std trait"
101 declare_clippy_lint! {
102 /// **What it does:** Checks for methods with certain name prefixes and which
103 /// doesn't match how self is taken. The actual rules are:
105 /// |Prefix |`self` taken |
106 /// |-------|----------------------|
107 /// |`as_` |`&self` or `&mut self`|
109 /// |`into_`|`self` |
110 /// |`is_` |`&self` or none |
111 /// |`to_` |`&self` |
113 /// **Why is this bad?** Consistency breeds readability. If you follow the
114 /// conventions, your users won't be surprised that they, e.g., need to supply a
115 /// mutable reference to a `as_..` function.
117 /// **Known problems:** None.
122 /// fn as_str(self) -> &str {
127 pub WRONG_SELF_CONVENTION,
129 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
132 declare_clippy_lint! {
133 /// **What it does:** This is the same as
134 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
136 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
138 /// **Known problems:** Actually *renaming* the function may break clients if
139 /// the function is part of the public interface. In that case, be mindful of
140 /// the stability guarantees you've given your users.
145 /// pub fn as_str(self) -> &str {
150 pub WRONG_PUB_SELF_CONVENTION,
152 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
155 declare_clippy_lint! {
156 /// **What it does:** Checks for usage of `ok().expect(..)`.
158 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
159 /// directly to get a better error message.
161 /// **Known problems:** The error type needs to implement `Debug`
165 /// x.ok().expect("why did I do this again?")
169 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
172 declare_clippy_lint! {
173 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
175 /// **Why is this bad?** Readability, this can be written more concisely as
176 /// `_.map_or(_, _)`.
178 /// **Known problems:** The order of the arguments is not in execution order
182 /// # let x = Some(1);
183 /// x.map(|a| a + 1).unwrap_or(0);
185 pub OPTION_MAP_UNWRAP_OR,
187 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as `map_or(a, f)`"
190 declare_clippy_lint! {
191 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
193 /// **Why is this bad?** Readability, this can be written more concisely as
194 /// `_.map_or_else(_, _)`.
196 /// **Known problems:** The order of the arguments is not in execution order.
200 /// # let x = Some(1);
201 /// # fn some_function() -> usize { 1 }
202 /// x.map(|a| a + 1).unwrap_or_else(some_function);
204 pub OPTION_MAP_UNWRAP_OR_ELSE,
206 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `map_or_else(g, f)`"
209 declare_clippy_lint! {
210 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
212 /// **Why is this bad?** Readability, this can be written more concisely as
213 /// `result.ok().map_or_else(_, _)`.
215 /// **Known problems:** None.
219 /// # let x: Result<usize, ()> = Ok(1);
220 /// # fn some_function(foo: ()) -> usize { 1 }
221 /// x.map(|a| a + 1).unwrap_or_else(some_function);
223 pub RESULT_MAP_UNWRAP_OR_ELSE,
225 "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `.ok().map_or_else(g, f)`"
228 declare_clippy_lint! {
229 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
231 /// **Why is this bad?** Readability, this can be written more concisely as
234 /// **Known problems:** The order of the arguments is not in execution order.
238 /// opt.map_or(None, |a| a + 1)
240 pub OPTION_MAP_OR_NONE,
242 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
245 declare_clippy_lint! {
246 /// **What it does:** Checks for usage of `_.filter(_).next()`.
248 /// **Why is this bad?** Readability, this can be written more concisely as
251 /// **Known problems:** None.
255 /// # let vec = vec![1];
256 /// vec.iter().filter(|x| **x == 0).next();
260 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
263 declare_clippy_lint! {
264 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
266 /// **Why is this bad?** Readability, this can be written more concisely as a
267 /// single method call.
269 /// **Known problems:**
273 /// let vec = vec![vec![1]];
274 /// vec.iter().map(|x| x.iter()).flatten();
278 "using combinations of `flatten` and `map` which can usually be written as a single method call"
281 declare_clippy_lint! {
282 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
283 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
285 /// **Why is this bad?** Readability, this can be written more concisely as a
286 /// single method call.
288 /// **Known problems:** Often requires a condition + Option/Iterator creation
289 /// inside the closure.
293 /// let vec = vec![1];
294 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
298 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
301 declare_clippy_lint! {
302 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
304 /// **Why is this bad?** Readability, this can be written more concisely as a
305 /// single method call.
307 /// **Known problems:** None
311 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
313 /// Can be written as
316 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
320 "using combination of `filter_map` and `next` which can usually be written as a single method call"
323 declare_clippy_lint! {
324 /// **What it does:** Checks for usage of `_.find(_).map(_)`.
326 /// **Why is this bad?** Readability, this can be written more concisely as a
327 /// single method call.
329 /// **Known problems:** Often requires a condition + Option/Iterator creation
330 /// inside the closure.
334 /// (0..3).find(|x| *x == 2).map(|x| x * 2);
336 /// Can be written as
338 /// (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
342 "using a combination of `find` and `map` can usually be written as a single method call"
345 declare_clippy_lint! {
346 /// **What it does:** Checks for an iterator search (such as `find()`,
347 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
349 /// **Why is this bad?** Readability, this can be written more concisely as
352 /// **Known problems:** None.
356 /// # let vec = vec![1];
357 /// vec.iter().find(|x| **x == 0).is_some();
361 "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
364 declare_clippy_lint! {
365 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
366 /// if it starts with a given char.
368 /// **Why is this bad?** Readability, this can be written more concisely as
369 /// `_.starts_with(_)`.
371 /// **Known problems:** None.
375 /// let name = "foo";
376 /// name.chars().next() == Some('_');
380 "using `.chars().next()` to check if a string starts with a char"
383 declare_clippy_lint! {
384 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
385 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
386 /// `unwrap_or_default` instead.
388 /// **Why is this bad?** The function will always be called and potentially
389 /// allocate an object acting as the default.
391 /// **Known problems:** If the function has side-effects, not calling it will
392 /// change the semantic of the program, but you shouldn't rely on that anyway.
396 /// # let foo = Some(String::new());
397 /// foo.unwrap_or(String::new());
399 /// this can instead be written:
401 /// # let foo = Some(String::new());
402 /// foo.unwrap_or_else(String::new);
406 /// # let foo = Some(String::new());
407 /// foo.unwrap_or_default();
411 "using any `*or` method with a function call, which suggests `*or_else`"
414 declare_clippy_lint! {
415 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
416 /// etc., and suggests to use `unwrap_or_else` instead
418 /// **Why is this bad?** The function will always be called.
420 /// **Known problems:** If the function has side-effects, not calling it will
421 /// change the semantics of the program, but you shouldn't rely on that anyway.
425 /// # let foo = Some(String::new());
426 /// # let err_code = "418";
427 /// # let err_msg = "I'm a teapot";
428 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
432 /// # let foo = Some(String::new());
433 /// # let err_code = "418";
434 /// # let err_msg = "I'm a teapot";
435 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
437 /// this can instead be written:
439 /// # let foo = Some(String::new());
440 /// # let err_code = "418";
441 /// # let err_msg = "I'm a teapot";
442 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
446 "using any `expect` method with a function call"
449 declare_clippy_lint! {
450 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
452 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
453 /// generics, not for using the `clone` method on a concrete type.
455 /// **Known problems:** None.
463 "using `clone` on a `Copy` type"
466 declare_clippy_lint! {
467 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
468 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
469 /// function syntax instead (e.g., `Rc::clone(foo)`).
471 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
472 /// can obscure the fact that only the pointer is being cloned, not the underlying
479 pub CLONE_ON_REF_PTR,
481 "using 'clone' on a ref-counted pointer"
484 declare_clippy_lint! {
485 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
487 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
488 /// cloning the underlying `T`.
490 /// **Known problems:** None.
497 /// let z = y.clone();
498 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
501 pub CLONE_DOUBLE_REF,
503 "using `clone` on `&&T`"
506 declare_clippy_lint! {
507 /// **What it does:** Checks for `new` not returning `Self`.
509 /// **Why is this bad?** As a convention, `new` methods are used to make a new
510 /// instance of a type.
512 /// **Known problems:** None.
517 /// fn new(..) -> NotAFoo {
523 "not returning `Self` in a `new` method"
526 declare_clippy_lint! {
527 /// **What it does:** Checks for string methods that receive a single-character
528 /// `str` as an argument, e.g., `_.split("x")`.
530 /// **Why is this bad?** Performing these methods using a `char` is faster than
533 /// **Known problems:** Does not catch multi-byte unicode characters.
536 /// `_.split("x")` could be `_.split('x')`
537 pub SINGLE_CHAR_PATTERN,
539 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
542 declare_clippy_lint! {
543 /// **What it does:** Checks for getting the inner pointer of a temporary
546 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
547 /// as the `CString` is alive.
549 /// **Known problems:** None.
553 /// let c_str = CString::new("foo").unwrap().as_ptr();
555 /// call_some_ffi_func(c_str);
558 /// Here `c_str` point to a freed address. The correct use would be:
560 /// let c_str = CString::new("foo").unwrap();
562 /// call_some_ffi_func(c_str.as_ptr());
565 pub TEMPORARY_CSTRING_AS_PTR,
567 "getting the inner pointer of a temporary `CString`"
570 declare_clippy_lint! {
571 /// **What it does:** Checks for use of `.iter().nth()` (and the related
572 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
574 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
577 /// **Known problems:** None.
581 /// let some_vec = vec![0, 1, 2, 3];
582 /// let bad_vec = some_vec.iter().nth(3);
583 /// let bad_slice = &some_vec[..].iter().nth(3);
585 /// The correct use would be:
587 /// let some_vec = vec![0, 1, 2, 3];
588 /// let bad_vec = some_vec.get(3);
589 /// let bad_slice = &some_vec[..].get(3);
593 "using `.iter().nth()` on a standard library type with O(1) element access"
596 declare_clippy_lint! {
597 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
599 /// **Why is this bad?** `.nth(x)` is cleaner
601 /// **Known problems:** None.
605 /// let some_vec = vec![0, 1, 2, 3];
606 /// let bad_vec = some_vec.iter().skip(3).next();
607 /// let bad_slice = &some_vec[..].iter().skip(3).next();
609 /// The correct use would be:
611 /// let some_vec = vec![0, 1, 2, 3];
612 /// let bad_vec = some_vec.iter().nth(3);
613 /// let bad_slice = &some_vec[..].iter().nth(3);
617 "using `.skip(x).next()` on an iterator"
620 declare_clippy_lint! {
621 /// **What it does:** Checks for use of `.get().unwrap()` (or
622 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
624 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
627 /// **Known problems:** Not a replacement for error handling: Using either
628 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
629 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
630 /// temporary placeholder for dealing with the `Option` type, then this does
631 /// not mitigate the need for error handling. If there is a chance that `.get()`
632 /// will be `None` in your program, then it is advisable that the `None` case
633 /// is handled in a future refactor instead of using `.unwrap()` or the Index
638 /// let mut some_vec = vec![0, 1, 2, 3];
639 /// let last = some_vec.get(3).unwrap();
640 /// *some_vec.get_mut(0).unwrap() = 1;
642 /// The correct use would be:
644 /// let mut some_vec = vec![0, 1, 2, 3];
645 /// let last = some_vec[3];
650 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
653 declare_clippy_lint! {
654 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
655 /// `&str` or `String`.
657 /// **Why is this bad?** `.push_str(s)` is clearer
659 /// **Known problems:** None.
664 /// let def = String::from("def");
665 /// let mut s = String::new();
666 /// s.extend(abc.chars());
667 /// s.extend(def.chars());
669 /// The correct use would be:
672 /// let def = String::from("def");
673 /// let mut s = String::new();
675 /// s.push_str(&def);
677 pub STRING_EXTEND_CHARS,
679 "using `x.extend(s.chars())` where s is a `&str` or `String`"
682 declare_clippy_lint! {
683 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
686 /// **Why is this bad?** `.to_vec()` is clearer
688 /// **Known problems:** None.
692 /// let s = [1, 2, 3, 4, 5];
693 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
695 /// The better use would be:
697 /// let s = [1, 2, 3, 4, 5];
698 /// let s2: Vec<isize> = s.to_vec();
700 pub ITER_CLONED_COLLECT,
702 "using `.cloned().collect()` on slice to create a `Vec`"
705 declare_clippy_lint! {
706 /// **What it does:** Checks for usage of `.chars().last()` or
707 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
709 /// **Why is this bad?** Readability, this can be written more concisely as
710 /// `_.ends_with(_)`.
712 /// **Known problems:** None.
716 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
720 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
723 declare_clippy_lint! {
724 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
725 /// types before and after the call are the same.
727 /// **Why is this bad?** The call is unnecessary.
729 /// **Known problems:** None.
733 /// # fn do_stuff(x: &[i32]) {}
734 /// let x: &[i32] = &[1, 2, 3, 4, 5];
735 /// do_stuff(x.as_ref());
737 /// The correct use would be:
739 /// # fn do_stuff(x: &[i32]) {}
740 /// let x: &[i32] = &[1, 2, 3, 4, 5];
745 "using `as_ref` where the types before and after the call are the same"
748 declare_clippy_lint! {
749 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
750 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
751 /// `sum` or `product`.
753 /// **Why is this bad?** Readability.
755 /// **Known problems:** False positive in pattern guards. Will be resolved once
756 /// non-lexical lifetimes are stable.
760 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
762 /// This could be written as:
764 /// let _ = (0..3).any(|x| x > 2);
766 pub UNNECESSARY_FOLD,
768 "using `fold` when a more succinct alternative exists"
771 declare_clippy_lint! {
772 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
773 /// More specifically it checks if the closure provided is only performing one of the
774 /// filter or map operations and suggests the appropriate option.
776 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
777 /// operation is being performed.
779 /// **Known problems:** None
783 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
785 /// As there is no transformation of the argument this could be written as:
787 /// let _ = (0..3).filter(|&x| x > 2);
791 /// let _ = (0..4).filter_map(i32::checked_abs);
793 /// As there is no conditional check on the argument this could be written as:
795 /// let _ = (0..4).map(i32::checked_abs);
797 pub UNNECESSARY_FILTER_MAP,
799 "using `filter_map` when a more succinct alternative exists"
802 declare_clippy_lint! {
803 /// **What it does:** Checks for `into_iter` calls on types which should be replaced by `iter` or
806 /// **Why is this bad?** Arrays and `PathBuf` do not yet have an `into_iter` method which move out
807 /// their content into an iterator. Auto-referencing resolves the `into_iter` call to its reference
808 /// instead, like `<&[T; N] as IntoIterator>::into_iter`, which just iterates over item references
809 /// like calling `iter` would. Furthermore, when the standard library actually
810 /// [implements the `into_iter` method](https://github.com/rust-lang/rust/issues/25725) which moves
811 /// the content out of the array, the original use of `into_iter` got inferred with the wrong type
812 /// and the code will be broken.
814 /// **Known problems:** None
819 /// let _ = [1, 2, 3].into_iter().map(|x| *x).collect::<Vec<u32>>();
821 pub INTO_ITER_ON_ARRAY,
823 "using `.into_iter()` on an array"
826 declare_clippy_lint! {
827 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
830 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
831 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
832 /// `iter_mut` directly.
834 /// **Known problems:** None
839 /// let _ = (&vec![3, 4, 5]).into_iter();
841 pub INTO_ITER_ON_REF,
843 "using `.into_iter()` on a reference"
846 declare_lint_pass!(Methods => [
849 SHOULD_IMPLEMENT_TRAIT,
850 WRONG_SELF_CONVENTION,
851 WRONG_PUB_SELF_CONVENTION,
853 OPTION_MAP_UNWRAP_OR,
854 OPTION_MAP_UNWRAP_OR_ELSE,
855 RESULT_MAP_UNWRAP_OR_ELSE,
867 TEMPORARY_CSTRING_AS_PTR,
880 UNNECESSARY_FILTER_MAP,
885 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
886 #[allow(clippy::cognitive_complexity)]
887 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
888 if in_macro(expr.span) {
892 let (method_names, arg_lists) = method_calls(expr, 2);
893 let method_names: Vec<LocalInternedString> = method_names.iter().map(|s| s.as_str()).collect();
894 let method_names: Vec<&str> = method_names.iter().map(std::convert::AsRef::as_ref).collect();
896 match method_names.as_slice() {
897 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
898 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
899 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
900 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
901 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0]),
902 ["unwrap_or_else", "map"] => lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]),
903 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
904 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
905 ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
906 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
907 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
908 ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
909 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
910 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
911 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
912 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0]),
913 ["is_some", "position"] => lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0]),
914 ["is_some", "rposition"] => lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0]),
915 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
916 ["as_ptr", "unwrap"] => lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0]),
917 ["nth", "iter"] => lint_iter_nth(cx, expr, arg_lists[1], false),
918 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, arg_lists[1], true),
919 ["next", "skip"] => lint_iter_skip_next(cx, expr),
920 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
921 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
922 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
923 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0]),
924 ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
929 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
930 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
931 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
933 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
934 if args.len() == 1 && method_call.ident.name == sym!(clone) {
935 lint_clone_on_copy(cx, expr, &args[0], self_ty);
936 lint_clone_on_ref_ptr(cx, expr, &args[0]);
940 ty::Ref(_, ty, _) if ty.sty == ty::Str => {
941 for &(method, pos) in &PATTERN_METHODS {
942 if method_call.ident.name.as_str() == method && args.len() > pos {
943 lint_single_char_pattern(cx, expr, &args[pos]);
947 ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
948 lint_into_iter(cx, expr, self_ty, *method_span);
953 hir::ExprKind::Binary(op, ref lhs, ref rhs)
954 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
956 let mut info = BinaryExprInfo {
960 eq: op.node == hir::BinOpKind::Eq,
962 lint_binary_expr_with_method_call(cx, &mut info);
968 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
969 if in_external_macro(cx.sess(), implitem.span) {
972 let name = implitem.ident.name.as_str();
973 let parent = cx.tcx.hir().get_parent_item(implitem.hir_id);
974 let item = cx.tcx.hir().expect_item(parent);
975 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
976 let ty = cx.tcx.type_of(def_id);
978 if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
979 if let Some(first_arg_ty) = sig.decl.inputs.get(0);
980 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
981 if let hir::ItemKind::Impl(_, _, _, _, None, ref self_ty, _) = item.node;
983 if cx.access_levels.is_exported(implitem.hir_id) {
984 // check missing trait implementations
985 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
986 if name == method_name &&
987 sig.decl.inputs.len() == n_args &&
988 out_type.matches(cx, &sig.decl.output) &&
989 self_kind.matches(cx, first_arg_ty, first_arg, self_ty, false, &implitem.generics) {
990 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, implitem.span, &format!(
991 "defining a method called `{}` on this type; consider implementing \
992 the `{}` trait or choosing a less ambiguous name", name, trait_name));
997 // check conventions w.r.t. conversion method names and predicates
998 let is_copy = is_copy(cx, ty);
999 for &(ref conv, self_kinds) in &CONVENTIONS {
1000 if conv.check(&name) {
1003 .any(|k| k.matches(cx, first_arg_ty, first_arg, self_ty, is_copy, &implitem.generics)) {
1004 let lint = if item.vis.node.is_pub() {
1005 WRONG_PUB_SELF_CONVENTION
1007 WRONG_SELF_CONVENTION
1012 &format!("methods called `{}` usually take {}; consider choosing a less \
1016 .map(|k| k.description())
1017 .collect::<Vec<_>>()
1021 // Only check the first convention to match (CONVENTIONS should be listed from most to least
1029 if let hir::ImplItemKind::Method(_, _) = implitem.node {
1030 let ret_ty = return_ty(cx, implitem.hir_id);
1032 // walk the return type and check for Self (this does not check associated types)
1033 for inner_type in ret_ty.walk() {
1034 if same_tys(cx, ty, inner_type) {
1039 // if return type is impl trait, check the associated types
1040 if let ty::Opaque(def_id, _) = ret_ty.sty {
1041 // one of the associated types must be Self
1042 for predicate in &cx.tcx.predicates_of(def_id).predicates {
1044 (Predicate::Projection(poly_projection_predicate), _) => {
1045 let binder = poly_projection_predicate.ty();
1046 let associated_type = binder.skip_binder();
1047 let associated_type_is_self_type = same_tys(cx, ty, associated_type);
1049 // if the associated type is self, early return and do not trigger lint
1050 if associated_type_is_self_type {
1059 if name == "new" && !same_tys(cx, ret_ty, ty) {
1064 "methods called `new` usually return `Self`",
1071 /// Checks for the `OR_FUN_CALL` lint.
1072 #[allow(clippy::too_many_lines)]
1073 fn lint_or_fun_call<'a, 'tcx>(
1074 cx: &LateContext<'a, 'tcx>,
1078 args: &'tcx [hir::Expr],
1080 // Searches an expression for method calls or function calls that aren't ctors
1081 struct FunCallFinder<'a, 'tcx> {
1082 cx: &'a LateContext<'a, 'tcx>,
1086 impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
1087 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
1088 let call_found = match &expr.node {
1089 // ignore enum and struct constructors
1090 hir::ExprKind::Call(..) => !is_ctor_function(self.cx, expr),
1091 hir::ExprKind::MethodCall(..) => true,
1096 // don't lint for constant values
1097 let owner_def = self.cx.tcx.hir().get_parent_did(expr.hir_id);
1098 let promotable = self
1101 .rvalue_promotable_map(owner_def)
1102 .contains(&expr.hir_id.local_id);
1109 intravisit::walk_expr(self, expr);
1113 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
1114 intravisit::NestedVisitorMap::None
1118 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1119 fn check_unwrap_or_default(
1120 cx: &LateContext<'_, '_>,
1123 self_expr: &hir::Expr,
1132 if name == "unwrap_or" {
1133 if let hir::ExprKind::Path(ref qpath) = fun.node {
1134 let path = &*last_path_segment(qpath).ident.as_str();
1136 if ["default", "new"].contains(&path) {
1137 let arg_ty = cx.tables.expr_ty(arg);
1138 let default_trait_id = if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT) {
1144 if implements_trait(cx, arg_ty, default_trait_id, &[]) {
1145 let mut applicability = Applicability::MachineApplicable;
1150 &format!("use of `{}` followed by a call to `{}`", name, path),
1153 "{}.unwrap_or_default()",
1154 snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
1167 /// Checks for `*or(foo())`.
1168 #[allow(clippy::too_many_arguments)]
1169 fn check_general_case<'a, 'tcx>(
1170 cx: &LateContext<'a, 'tcx>,
1174 self_expr: &hir::Expr,
1175 arg: &'tcx hir::Expr,
1179 // (path, fn_has_argument, methods, suffix)
1180 let know_types: &[(&[_], _, &[_], _)] = &[
1181 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1182 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1183 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1184 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1187 // early check if the name is one we care about
1188 if know_types.iter().all(|k| !k.2.contains(&name)) {
1192 let mut finder = FunCallFinder { cx: &cx, found: false };
1193 finder.visit_expr(&arg);
1198 let self_ty = cx.tables.expr_ty(self_expr);
1200 let (fn_has_arguments, poss, suffix) = if let Some(&(_, fn_has_arguments, poss, suffix)) =
1201 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0))
1203 (fn_has_arguments, poss, suffix)
1208 if !poss.contains(&name) {
1212 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1213 (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1214 (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1215 (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1217 let span_replace_word = method_span.with_hi(span.hi());
1222 &format!("use of `{}` followed by a function call", name),
1224 format!("{}_{}({})", name, suffix, sugg),
1225 Applicability::HasPlaceholders,
1229 if args.len() == 2 {
1230 match args[1].node {
1231 hir::ExprKind::Call(ref fun, ref or_args) => {
1232 let or_has_args = !or_args.is_empty();
1233 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1246 hir::ExprKind::MethodCall(_, span, ref or_args) => check_general_case(
1253 !or_args.is_empty(),
1261 /// Checks for the `EXPECT_FUN_CALL` lint.
1262 #[allow(clippy::too_many_lines)]
1263 fn lint_expect_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
1264 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1266 fn get_arg_root<'a>(cx: &LateContext<'_, '_>, arg: &'a hir::Expr) -> &'a hir::Expr {
1267 let mut arg_root = arg;
1269 arg_root = match &arg_root.node {
1270 hir::ExprKind::AddrOf(_, expr) => expr,
1271 hir::ExprKind::MethodCall(method_name, _, call_args) => {
1272 if call_args.len() == 1
1273 && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1275 let arg_type = cx.tables.expr_ty(&call_args[0]);
1276 let base_type = walk_ptrs_ty(arg_type);
1277 base_type.sty == ty::Str || match_type(cx, base_type, &paths::STRING)
1291 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1292 // converted to string.
1293 fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr) -> bool {
1294 let arg_ty = cx.tables.expr_ty(arg);
1295 if match_type(cx, arg_ty, &paths::STRING) {
1298 if let ty::Ref(ty::ReStatic, ty, ..) = arg_ty.sty {
1299 if ty.sty == ty::Str {
1306 fn generate_format_arg_snippet(
1307 cx: &LateContext<'_, '_>,
1309 applicability: &mut Applicability,
1311 if let hir::ExprKind::AddrOf(_, ref format_arg) = a.node {
1312 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.node {
1313 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.node {
1314 return format_arg_expr_tup
1316 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1325 fn is_call(node: &hir::ExprKind) -> bool {
1327 hir::ExprKind::AddrOf(_, expr) => {
1330 hir::ExprKind::Call(..)
1331 | hir::ExprKind::MethodCall(..)
1332 // These variants are debatable or require further examination
1333 | hir::ExprKind::Match(..)
1334 | hir::ExprKind::Block{ .. } => true,
1339 if args.len() != 2 || name != "expect" || !is_call(&args[1].node) {
1343 let receiver_type = cx.tables.expr_ty(&args[0]);
1344 let closure_args = if match_type(cx, receiver_type, &paths::OPTION) {
1346 } else if match_type(cx, receiver_type, &paths::RESULT) {
1352 let arg_root = get_arg_root(cx, &args[1]);
1354 let span_replace_word = method_span.with_hi(expr.span.hi());
1356 let mut applicability = Applicability::MachineApplicable;
1358 //Special handling for `format!` as arg_root
1359 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.node {
1360 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1 {
1361 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].node {
1362 let fmt_spec = &format_args[0];
1363 let fmt_args = &format_args[1];
1365 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1367 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1369 let sugg = args.join(", ");
1375 &format!("use of `{}` followed by a function call", name),
1377 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1386 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1387 if requires_to_string(cx, arg_root) {
1388 arg_root_snippet.to_mut().push_str(".to_string()");
1395 &format!("use of `{}` followed by a function call", name),
1397 format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1402 /// Checks for the `CLONE_ON_COPY` lint.
1403 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty<'_>) {
1404 let ty = cx.tables.expr_ty(expr);
1405 if let ty::Ref(_, inner, _) = arg_ty.sty {
1406 if let ty::Ref(_, innermost, _) = inner.sty {
1411 "using `clone` on a double-reference; \
1412 this will copy the reference instead of cloning the inner type",
1414 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1415 let mut ty = innermost;
1417 while let ty::Ref(_, inner, _) = ty.sty {
1421 let refs: String = iter::repeat('&').take(n + 1).collect();
1422 let derefs: String = iter::repeat('*').take(n).collect();
1423 let explicit = format!("{}{}::clone({})", refs, ty, snip);
1426 "try dereferencing it",
1427 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1428 Applicability::MaybeIncorrect,
1432 "or try being explicit about what type to clone",
1434 Applicability::MaybeIncorrect,
1439 return; // don't report clone_on_copy
1443 if is_copy(cx, ty) {
1445 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1446 // x.clone() might have dereferenced x, possibly through Deref impls
1447 if cx.tables.expr_ty(arg) == ty {
1448 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1450 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
1451 match cx.tcx.hir().get(parent) {
1452 hir::Node::Expr(parent) => match parent.node {
1453 // &*x is a nop, &x.clone() is not
1454 hir::ExprKind::AddrOf(..) |
1455 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1456 hir::ExprKind::MethodCall(..) => return,
1459 hir::Node::Stmt(stmt) => {
1460 if let hir::StmtKind::Local(ref loc) = stmt.node {
1461 if let hir::PatKind::Ref(..) = loc.pat.node {
1462 // let ref y = *x borrows x, let ref y = x.clone() does not
1470 let deref_count = cx
1472 .expr_adjustments(arg)
1475 if let ty::adjustment::Adjust::Deref(_) = adj.kind {
1482 let derefs: String = iter::repeat('*').take(deref_count).collect();
1483 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
1488 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1489 if let Some((text, snip)) = snip {
1490 db.span_suggestion(expr.span, text, snip, Applicability::Unspecified);
1496 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr) {
1497 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1499 if let ty::Adt(_, subst) = obj_ty.sty {
1500 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1502 } else if match_type(cx, obj_ty, &paths::ARC) {
1504 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1514 "using '.clone()' on a ref-counted pointer",
1517 "{}::<{}>::clone(&{})",
1520 snippet(cx, arg.span, "_")
1522 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
1527 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1529 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1530 let target = &arglists[0][0];
1531 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
1532 let ref_str = if self_ty.sty == ty::Str {
1534 } else if match_type(cx, self_ty, &paths::STRING) {
1540 let mut applicability = Applicability::MachineApplicable;
1543 STRING_EXTEND_CHARS,
1545 "calling `.extend(_.chars())`",
1548 "{}.push_str({}{})",
1549 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
1551 snippet_with_applicability(cx, target.span, "_", &mut applicability)
1558 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
1559 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
1560 if match_type(cx, obj_ty, &paths::STRING) {
1561 lint_string_extend(cx, expr, args);
1565 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
1567 if let hir::ExprKind::Call(ref fun, ref args) = new.node;
1569 if let hir::ExprKind::Path(ref path) = fun.node;
1570 if let Res::Def(DefKind::Method, did) = cx.tables.qpath_res(path, fun.hir_id);
1571 if match_def_path(cx, did, &paths::CSTRING_NEW);
1575 TEMPORARY_CSTRING_AS_PTR,
1577 "you are getting the inner pointer of a temporary `CString`",
1579 db.note("that pointer will be invalid outside this expression");
1580 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
1586 fn lint_iter_cloned_collect<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr, iter_args: &'tcx [hir::Expr]) {
1587 if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC) {
1588 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])) {
1589 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite()) {
1592 ITER_CLONED_COLLECT,
1594 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
1597 ".to_vec()".to_string(),
1598 Applicability::MachineApplicable,
1605 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr, fold_args: &[hir::Expr]) {
1606 fn check_fold_with_op(
1607 cx: &LateContext<'_, '_>,
1608 fold_args: &[hir::Expr],
1610 replacement_method_name: &str,
1611 replacement_has_args: bool,
1614 // Extract the body of the closure passed to fold
1615 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].node;
1616 let closure_body = cx.tcx.hir().body(body_id);
1617 let closure_expr = remove_blocks(&closure_body.value);
1619 // Check if the closure body is of the form `acc <op> some_expr(x)`
1620 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.node;
1621 if bin_op.node == op;
1623 // Extract the names of the two arguments to the closure
1624 if let Some(first_arg_ident) = get_arg_name(&closure_body.arguments[0].pat);
1625 if let Some(second_arg_ident) = get_arg_name(&closure_body.arguments[1].pat);
1627 if match_var(&*left_expr, first_arg_ident);
1628 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
1631 // Span containing `.fold(...)`
1632 let next_point = cx.sess().source_map().next_point(fold_args[0].span);
1633 let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
1635 let mut applicability = Applicability::MachineApplicable;
1636 let sugg = if replacement_has_args {
1638 ".{replacement}(|{s}| {r})",
1639 replacement = replacement_method_name,
1640 s = second_arg_ident,
1641 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
1646 replacement = replacement_method_name,
1654 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
1655 "this `.fold` can be written more succinctly using another method",
1664 // Check that this is a call to Iterator::fold rather than just some function called fold
1665 if !match_trait_method(cx, expr, &paths::ITERATOR) {
1670 fold_args.len() == 3,
1671 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
1674 // Check if the first argument to .fold is a suitable literal
1675 if let hir::ExprKind::Lit(ref lit) = fold_args[1].node {
1677 ast::LitKind::Bool(false) => check_fold_with_op(cx, fold_args, hir::BinOpKind::Or, "any", true),
1678 ast::LitKind::Bool(true) => check_fold_with_op(cx, fold_args, hir::BinOpKind::And, "all", true),
1679 ast::LitKind::Int(0, _) => check_fold_with_op(cx, fold_args, hir::BinOpKind::Add, "sum", false),
1680 ast::LitKind::Int(1, _) => check_fold_with_op(cx, fold_args, hir::BinOpKind::Mul, "product", false),
1686 fn lint_iter_nth<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr, iter_args: &'tcx [hir::Expr], is_mut: bool) {
1687 let mut_str = if is_mut { "_mut" } else { "" };
1688 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
1690 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC) {
1692 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
1695 return; // caller is not a type that we want to lint
1703 "called `.iter{0}().nth()` on a {1}. Calling `.get{0}()` is both faster and more readable",
1704 mut_str, caller_type
1709 fn lint_get_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr, get_args: &'tcx [hir::Expr], is_mut: bool) {
1710 // Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
1711 // because they do not implement `IndexMut`
1712 let mut applicability = Applicability::MachineApplicable;
1713 let expr_ty = cx.tables.expr_ty(&get_args[0]);
1714 let get_args_str = if get_args.len() > 1 {
1715 snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
1717 return; // not linting on a .get().unwrap() chain or variant
1720 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
1721 needs_ref = get_args_str.parse::<usize>().is_ok();
1723 } else if match_type(cx, expr_ty, &paths::VEC) {
1724 needs_ref = get_args_str.parse::<usize>().is_ok();
1726 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
1727 needs_ref = get_args_str.parse::<usize>().is_ok();
1729 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
1732 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
1736 return; // caller is not a type that we want to lint
1739 let mut span = expr.span;
1741 // Handle the case where the result is immediately dereferenced
1742 // by not requiring ref and pulling the dereference into the
1746 if let Some(parent) = get_parent_expr(cx, expr);
1747 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.node;
1754 let mut_str = if is_mut { "_mut" } else { "" };
1755 let borrow_str = if !needs_ref {
1768 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
1769 mut_str, caller_type
1775 snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
1782 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr) {
1783 // lint if caller of skip is an Iterator
1784 if match_trait_method(cx, expr, &paths::ITERATOR) {
1789 "called `skip(x).next()` on an iterator. This is more succinctly expressed by calling `nth(x)`",
1794 fn derefs_to_slice<'a, 'tcx>(
1795 cx: &LateContext<'a, 'tcx>,
1796 expr: &'tcx hir::Expr,
1798 ) -> Option<&'tcx hir::Expr> {
1799 fn may_slice<'a>(cx: &LateContext<'_, 'a>, ty: Ty<'a>) -> bool {
1801 ty::Slice(_) => true,
1802 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
1803 ty::Adt(..) => match_type(cx, ty, &paths::VEC),
1804 ty::Array(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
1805 ty::Ref(_, inner, _) => may_slice(cx, inner),
1810 if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.node {
1811 if path.ident.name == sym!(iter) && may_slice(cx, cx.tables.expr_ty(&args[0])) {
1818 ty::Slice(_) => Some(expr),
1819 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
1820 ty::Ref(_, inner, _) => {
1821 if may_slice(cx, inner) {
1832 /// lint use of `unwrap()` for `Option`s and `Result`s
1833 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
1834 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
1836 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
1837 Some((OPTION_UNWRAP_USED, "an Option", "None"))
1838 } else if match_type(cx, obj_ty, &paths::RESULT) {
1839 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
1844 if let Some((lint, kind, none_value)) = mess {
1850 "used unwrap() on {} value. If you don't want to handle the {} case gracefully, consider \
1851 using expect() to provide a better panic \
1859 /// lint use of `ok().expect()` for `Result`s
1860 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr, ok_args: &[hir::Expr]) {
1861 // lint if the caller of `ok()` is a `Result`
1862 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
1863 let result_type = cx.tables.expr_ty(&ok_args[0]);
1864 if let Some(error_type) = get_error_type(cx, result_type) {
1865 if has_debug_impl(error_type, cx) {
1870 "called `ok().expect()` on a Result value. You can call `expect` directly on the `Result`",
1877 /// lint use of `map().flatten()` for `Iterators`
1878 fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_args: &'tcx [hir::Expr]) {
1879 // lint if caller of `.map().flatten()` is an Iterator
1880 if match_trait_method(cx, expr, &paths::ITERATOR) {
1881 let msg = "called `map(..).flatten()` on an `Iterator`. \
1882 This is more succinctly expressed by calling `.flat_map(..)`";
1883 let self_snippet = snippet(cx, map_args[0].span, "..");
1884 let func_snippet = snippet(cx, map_args[1].span, "..");
1885 let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
1886 span_lint_and_then(cx, MAP_FLATTEN, expr.span, msg, |db| {
1889 "try using flat_map instead",
1891 Applicability::MachineApplicable,
1897 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
1898 fn lint_map_unwrap_or_else<'a, 'tcx>(
1899 cx: &LateContext<'a, 'tcx>,
1900 expr: &'tcx hir::Expr,
1901 map_args: &'tcx [hir::Expr],
1902 unwrap_args: &'tcx [hir::Expr],
1904 // lint if the caller of `map()` is an `Option`
1905 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
1906 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
1908 if is_option || is_result {
1909 // Don't make a suggestion that may fail to compile due to mutably borrowing
1910 // the same variable twice.
1911 let map_mutated_vars = mutated_variables(&map_args[0], cx);
1912 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
1913 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
1914 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
1922 let msg = if is_option {
1923 "called `map(f).unwrap_or_else(g)` on an Option value. This can be done more directly by calling \
1924 `map_or_else(g, f)` instead"
1926 "called `map(f).unwrap_or_else(g)` on a Result value. This can be done more directly by calling \
1927 `ok().map_or_else(g, f)` instead"
1929 // get snippets for args to map() and unwrap_or_else()
1930 let map_snippet = snippet(cx, map_args[1].span, "..");
1931 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
1932 // lint, with note if neither arg is > 1 line and both map() and
1933 // unwrap_or_else() have the same span
1934 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
1935 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
1936 if same_span && !multiline {
1940 OPTION_MAP_UNWRAP_OR_ELSE
1942 RESULT_MAP_UNWRAP_OR_ELSE
1948 "replace `map({0}).unwrap_or_else({1})` with `{2}map_or_else({1}, {0})`",
1951 if is_result { "ok()." } else { "" }
1954 } else if same_span && multiline {
1958 OPTION_MAP_UNWRAP_OR_ELSE
1960 RESULT_MAP_UNWRAP_OR_ELSE
1969 /// lint use of `_.map_or(None, _)` for `Option`s
1970 fn lint_map_or_none<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, map_or_args: &'tcx [hir::Expr]) {
1971 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
1972 // check if the first non-self argument to map_or() is None
1973 let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].node {
1974 match_qpath(qpath, &paths::OPTION_NONE)
1979 if map_or_arg_is_none {
1981 let msg = "called `map_or(None, f)` on an Option value. This can be done more directly by calling \
1982 `and_then(f)` instead";
1983 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
1984 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
1985 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
1986 span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
1989 "try using and_then instead",
1991 Applicability::MachineApplicable, // snippet
1998 /// lint use of `filter().next()` for `Iterators`
1999 fn lint_filter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
2000 // lint if caller of `.filter().next()` is an Iterator
2001 if match_trait_method(cx, expr, &paths::ITERATOR) {
2002 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2003 `.find(p)` instead.";
2004 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2005 if filter_snippet.lines().count() <= 1 {
2006 // add note if not multi-line
2013 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2016 span_lint(cx, FILTER_NEXT, expr.span, msg);
2021 /// lint use of `filter().map()` for `Iterators`
2022 fn lint_filter_map<'a, 'tcx>(
2023 cx: &LateContext<'a, 'tcx>,
2024 expr: &'tcx hir::Expr,
2025 _filter_args: &'tcx [hir::Expr],
2026 _map_args: &'tcx [hir::Expr],
2028 // lint if caller of `.filter().map()` is an Iterator
2029 if match_trait_method(cx, expr, &paths::ITERATOR) {
2030 let msg = "called `filter(p).map(q)` on an `Iterator`. \
2031 This is more succinctly expressed by calling `.filter_map(..)` instead.";
2032 span_lint(cx, FILTER_MAP, expr.span, msg);
2036 /// lint use of `filter_map().next()` for `Iterators`
2037 fn lint_filter_map_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, filter_args: &'tcx [hir::Expr]) {
2038 if match_trait_method(cx, expr, &paths::ITERATOR) {
2039 let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2040 `.find_map(p)` instead.";
2041 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2042 if filter_snippet.lines().count() <= 1 {
2049 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2052 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2057 /// lint use of `find().map()` for `Iterators`
2058 fn lint_find_map<'a, 'tcx>(
2059 cx: &LateContext<'a, 'tcx>,
2060 expr: &'tcx hir::Expr,
2061 _find_args: &'tcx [hir::Expr],
2062 map_args: &'tcx [hir::Expr],
2064 // lint if caller of `.filter().map()` is an Iterator
2065 if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2066 let msg = "called `find(p).map(q)` on an `Iterator`. \
2067 This is more succinctly expressed by calling `.find_map(..)` instead.";
2068 span_lint(cx, FIND_MAP, expr.span, msg);
2072 /// lint use of `filter().map()` for `Iterators`
2073 fn lint_filter_map_map<'a, 'tcx>(
2074 cx: &LateContext<'a, 'tcx>,
2075 expr: &'tcx hir::Expr,
2076 _filter_args: &'tcx [hir::Expr],
2077 _map_args: &'tcx [hir::Expr],
2079 // lint if caller of `.filter().map()` is an Iterator
2080 if match_trait_method(cx, expr, &paths::ITERATOR) {
2081 let msg = "called `filter_map(p).map(q)` on an `Iterator`. \
2082 This is more succinctly expressed by only calling `.filter_map(..)` instead.";
2083 span_lint(cx, FILTER_MAP, expr.span, msg);
2087 /// lint use of `filter().flat_map()` for `Iterators`
2088 fn lint_filter_flat_map<'a, 'tcx>(
2089 cx: &LateContext<'a, 'tcx>,
2090 expr: &'tcx hir::Expr,
2091 _filter_args: &'tcx [hir::Expr],
2092 _map_args: &'tcx [hir::Expr],
2094 // lint if caller of `.filter().flat_map()` is an Iterator
2095 if match_trait_method(cx, expr, &paths::ITERATOR) {
2096 let msg = "called `filter(p).flat_map(q)` on an `Iterator`. \
2097 This is more succinctly expressed by calling `.flat_map(..)` \
2098 and filtering by returning an empty Iterator.";
2099 span_lint(cx, FILTER_MAP, expr.span, msg);
2103 /// lint use of `filter_map().flat_map()` for `Iterators`
2104 fn lint_filter_map_flat_map<'a, 'tcx>(
2105 cx: &LateContext<'a, 'tcx>,
2106 expr: &'tcx hir::Expr,
2107 _filter_args: &'tcx [hir::Expr],
2108 _map_args: &'tcx [hir::Expr],
2110 // lint if caller of `.filter_map().flat_map()` is an Iterator
2111 if match_trait_method(cx, expr, &paths::ITERATOR) {
2112 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`. \
2113 This is more succinctly expressed by calling `.flat_map(..)` \
2114 and filtering by returning an empty Iterator.";
2115 span_lint(cx, FILTER_MAP, expr.span, msg);
2119 /// lint searching an Iterator followed by `is_some()`
2120 fn lint_search_is_some<'a, 'tcx>(
2121 cx: &LateContext<'a, 'tcx>,
2122 expr: &'tcx hir::Expr,
2123 search_method: &str,
2124 search_args: &'tcx [hir::Expr],
2125 is_some_args: &'tcx [hir::Expr],
2127 // lint if caller of search is an Iterator
2128 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2130 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2131 expressed by calling `any()`.",
2134 let search_snippet = snippet(cx, search_args[1].span, "..");
2135 if search_snippet.lines().count() <= 1 {
2136 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2137 let any_search_snippet = if_chain! {
2138 if search_method == "find";
2139 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].node;
2140 let closure_body = cx.tcx.hir().body(body_id);
2141 if let Some(closure_arg) = closure_body.arguments.get(0);
2142 if let hir::PatKind::Ref(..) = closure_arg.pat.node;
2144 Some(search_snippet.replacen('&', "", 1))
2149 // add note if not multi-line
2157 "replace `{0}({1}).is_some()` with `any({2})`",
2160 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2164 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2169 /// Used for `lint_binary_expr_with_method_call`.
2170 #[derive(Copy, Clone)]
2171 struct BinaryExprInfo<'a> {
2172 expr: &'a hir::Expr,
2173 chain: &'a hir::Expr,
2174 other: &'a hir::Expr,
2178 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2179 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
2180 macro_rules! lint_with_both_lhs_and_rhs {
2181 ($func:ident, $cx:expr, $info:ident) => {
2182 if !$func($cx, $info) {
2183 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2184 if $func($cx, $info) {
2191 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2192 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2193 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2194 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2197 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2199 cx: &LateContext<'_, '_>,
2200 info: &BinaryExprInfo<'_>,
2201 chain_methods: &[&str],
2202 lint: &'static Lint,
2206 if let Some(args) = method_chain_args(info.chain, chain_methods);
2207 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.node;
2208 if arg_char.len() == 1;
2209 if let hir::ExprKind::Path(ref qpath) = fun.node;
2210 if let Some(segment) = single_segment_path(qpath);
2211 if segment.ident.name == sym!(Some);
2213 let mut applicability = Applicability::MachineApplicable;
2214 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
2216 if self_ty.sty != ty::Str {
2224 &format!("you should use the `{}` method", suggest),
2226 format!("{}{}.{}({})",
2227 if info.eq { "" } else { "!" },
2228 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2230 snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
2241 /// Checks for the `CHARS_NEXT_CMP` lint.
2242 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2243 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2246 /// Checks for the `CHARS_LAST_CMP` lint.
2247 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2248 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2251 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2255 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2256 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
2257 cx: &LateContext<'a, 'tcx>,
2258 info: &BinaryExprInfo<'_>,
2259 chain_methods: &[&str],
2260 lint: &'static Lint,
2264 if let Some(args) = method_chain_args(info.chain, chain_methods);
2265 if let hir::ExprKind::Lit(ref lit) = info.other.node;
2266 if let ast::LitKind::Char(c) = lit.node;
2268 let mut applicability = Applicability::MachineApplicable;
2273 &format!("you should use the `{}` method", suggest),
2275 format!("{}{}.{}('{}')",
2276 if info.eq { "" } else { "!" },
2277 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2290 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2291 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2292 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2295 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2296 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2297 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
2300 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
2304 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
2305 fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, _expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
2307 if let hir::ExprKind::Lit(lit) = &arg.node;
2308 if let ast::LitKind::Str(r, _) = lit.node;
2309 if r.as_str().len() == 1;
2311 let mut applicability = Applicability::MachineApplicable;
2312 let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
2313 let c = &snip[1..snip.len() - 1];
2314 let hint = format!("'{}'", if c == "'" { "\\'" } else { c });
2317 SINGLE_CHAR_PATTERN,
2319 "single-character string constant used as pattern",
2320 "try using a char instead",
2328 /// Checks for the `USELESS_ASREF` lint.
2329 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
2330 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
2331 // check if the call is to the actual `AsRef` or `AsMut` trait
2332 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
2333 // check if the type after `as_ref` or `as_mut` is the same as before
2334 let recvr = &as_ref_args[0];
2335 let rcv_ty = cx.tables.expr_ty(recvr);
2336 let res_ty = cx.tables.expr_ty(expr);
2337 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
2338 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
2339 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
2340 // allow the `as_ref` or `as_mut` if it is followed by another method call
2342 if let Some(parent) = get_parent_expr(cx, expr);
2343 if let hir::ExprKind::MethodCall(_, ref span, _) = parent.node;
2344 if span != &expr.span;
2350 let mut applicability = Applicability::MachineApplicable;
2355 &format!("this call to `{}` does nothing", call_name),
2357 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
2364 fn ty_has_iter_method(
2365 cx: &LateContext<'_, '_>,
2366 self_ref_ty: Ty<'_>,
2367 ) -> Option<(&'static Lint, &'static str, &'static str)> {
2368 if let Some(ty_name) = has_iter_method(cx, self_ref_ty) {
2369 let lint = if ty_name == "array" || ty_name == "PathBuf" {
2374 let mutbl = match self_ref_ty.sty {
2375 ty::Ref(_, _, mutbl) => mutbl,
2376 _ => unreachable!(),
2378 let method_name = match mutbl {
2379 hir::MutImmutable => "iter",
2380 hir::MutMutable => "iter_mut",
2382 Some((lint, ty_name, method_name))
2388 fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr, self_ref_ty: Ty<'_>, method_span: Span) {
2389 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
2392 if let Some((lint, kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
2398 "this .into_iter() call is equivalent to .{}() and will not move the {}",
2402 method_name.to_string(),
2403 Applicability::MachineApplicable,
2408 /// Given a `Result<T, E>` type, return its error type (`E`).
2409 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
2410 if let ty::Adt(_, substs) = ty.sty {
2411 if match_type(cx, ty, &paths::RESULT) {
2412 substs.types().nth(1)
2421 /// This checks whether a given type is known to implement Debug.
2422 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
2423 match cx.tcx.lang_items().debug_trait() {
2424 Some(debug) => implements_trait(cx, ty, debug, &[]),
2431 StartsWith(&'static str),
2435 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
2436 (Convention::Eq("new"), &[SelfKind::No]),
2437 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
2438 (Convention::StartsWith("from_"), &[SelfKind::No]),
2439 (Convention::StartsWith("into_"), &[SelfKind::Value]),
2440 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
2441 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
2442 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
2446 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
2447 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
2448 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
2449 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
2450 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
2451 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
2452 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
2453 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
2454 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
2455 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
2456 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
2457 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
2458 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
2459 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
2460 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
2461 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
2462 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
2463 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
2464 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
2465 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
2466 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
2467 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
2468 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
2469 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
2470 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
2471 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
2472 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
2473 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
2474 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
2475 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
2476 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
2480 const PATTERN_METHODS: [(&str, usize); 17] = [
2488 ("split_terminator", 1),
2489 ("rsplit_terminator", 1),
2494 ("match_indices", 1),
2495 ("rmatch_indices", 1),
2496 ("trim_start_matches", 1),
2497 ("trim_end_matches", 1),
2500 #[derive(Clone, Copy, PartialEq, Debug)]
2511 cx: &LateContext<'_, '_>,
2515 allow_value_for_ref: bool,
2516 generics: &hir::Generics,
2518 // Self types in the HIR are desugared to explicit self types. So it will
2521 // where SomeType can be `Self` or an explicit impl self type (e.g., `Foo` if
2522 // the impl is on `Foo`)
2523 // Thus, we only need to test equality against the impl self type or if it is
2525 // `Self`. Furthermore, the only possible types for `self: ` are `&Self`,
2526 // `Self`, `&mut Self`,
2527 // and `Box<Self>`, including the equivalent types with `Foo`.
2529 let is_actually_self = |ty| is_self_ty(ty) || SpanlessEq::new(cx).eq_ty(ty, self_ty);
2532 Self::Value => is_actually_self(ty),
2533 Self::Ref | Self::RefMut => {
2534 if allow_value_for_ref && is_actually_self(ty) {
2538 hir::TyKind::Rptr(_, ref mt_ty) => {
2539 let mutability_match = if self == Self::Ref {
2540 mt_ty.mutbl == hir::MutImmutable
2542 mt_ty.mutbl == hir::MutMutable
2544 is_actually_self(&mt_ty.ty) && mutability_match
2553 Self::Value => false,
2554 Self::Ref => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASREF_TRAIT),
2555 Self::RefMut => is_as_ref_or_mut_trait(ty, self_ty, generics, &paths::ASMUT_TRAIT),
2561 fn description(self) -> &'static str {
2563 Self::Value => "self by value",
2564 Self::Ref => "self by reference",
2565 Self::RefMut => "self by mutable reference",
2566 Self::No => "no self",
2571 fn is_as_ref_or_mut_trait(ty: &hir::Ty, self_ty: &hir::Ty, generics: &hir::Generics, name: &[&str]) -> bool {
2572 single_segment_ty(ty).map_or(false, |seg| {
2573 generics.params.iter().any(|param| match param.kind {
2574 hir::GenericParamKind::Type { .. } => {
2575 param.name.ident().name == seg.ident.name
2576 && param.bounds.iter().any(|bound| {
2577 if let hir::GenericBound::Trait(ref ptr, ..) = *bound {
2578 let path = &ptr.trait_ref.path;
2579 match_path(path, name)
2580 && path.segments.last().map_or(false, |s| {
2581 if let Some(ref params) = s.args {
2582 if params.parenthesized {
2585 // FIXME(flip1995): messy, improve if there is a better option
2587 let types: Vec<_> = params
2590 .filter_map(|arg| match arg {
2591 hir::GenericArg::Type(ty) => Some(ty),
2595 types.len() == 1 && (is_self_ty(&types[0]) || is_ty(&*types[0], self_ty))
2611 fn is_ty(ty: &hir::Ty, self_ty: &hir::Ty) -> bool {
2612 match (&ty.node, &self_ty.node) {
2614 &hir::TyKind::Path(hir::QPath::Resolved(_, ref ty_path)),
2615 &hir::TyKind::Path(hir::QPath::Resolved(_, ref self_ty_path)),
2619 .map(|seg| seg.ident.name)
2620 .eq(self_ty_path.segments.iter().map(|seg| seg.ident.name)),
2625 fn single_segment_ty(ty: &hir::Ty) -> Option<&hir::PathSegment> {
2626 if let hir::TyKind::Path(ref path) = ty.node {
2627 single_segment_path(path)
2634 fn check(&self, other: &str) -> bool {
2636 Self::Eq(this) => this == other,
2637 Self::StartsWith(this) => other.starts_with(this) && this != other,
2642 impl fmt::Display for Convention {
2643 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
2645 Self::Eq(this) => this.fmt(f),
2646 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
2651 #[derive(Clone, Copy)]
2660 fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FunctionRetTy) -> bool {
2661 let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyKind::Tup(vec![].into()));
2663 (Self::Unit, &hir::DefaultReturn(_)) => true,
2664 (Self::Unit, &hir::Return(ref ty)) if is_unit(ty) => true,
2665 (Self::Bool, &hir::Return(ref ty)) if is_bool(ty) => true,
2666 (Self::Any, &hir::Return(ref ty)) if !is_unit(ty) => true,
2667 (Self::Ref, &hir::Return(ref ty)) => matches!(ty.node, hir::TyKind::Rptr(_, _)),
2673 fn is_bool(ty: &hir::Ty) -> bool {
2674 if let hir::TyKind::Path(ref p) = ty.node {
2675 match_qpath(p, &["bool"])