1 mod bind_instead_of_map;
2 mod inefficient_to_string;
3 mod manual_saturating_arithmetic;
4 mod option_map_unwrap_or;
5 mod unnecessary_filter_map;
11 use bind_instead_of_map::BindInsteadOfMap;
12 use if_chain::if_chain;
14 use rustc_errors::Applicability;
16 use rustc_hir::intravisit::{self, Visitor};
17 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::lint::in_external_macro;
20 use rustc_middle::ty::subst::GenericArgKind;
21 use rustc_middle::ty::{self, Ty, TyS};
22 use rustc_session::{declare_lint_pass, declare_tool_lint};
23 use rustc_span::source_map::Span;
24 use rustc_span::symbol::{sym, SymbolStr};
26 use crate::consts::{constant, Constant};
27 use crate::utils::usage::mutated_variables;
29 get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait, in_macro, is_copy,
30 is_ctor_or_promotable_const_function, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
31 match_def_path, match_qpath, match_trait_method, match_type, match_var, method_calls, method_chain_args, paths,
32 remove_blocks, return_ty, single_segment_path, snippet, snippet_with_applicability, snippet_with_macro_callsite,
33 span_lint, span_lint_and_help, span_lint_and_note, span_lint_and_sugg, span_lint_and_then, sugg, walk_ptrs_ty,
34 walk_ptrs_ty_depth, SpanlessEq,
37 declare_clippy_lint! {
38 /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
40 /// **Why is this bad?** It is better to handle the `None` or `Err` case,
41 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
42 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
43 /// `Allow` by default.
45 /// `result.unwrap()` will let the thread panic on `Err` values.
46 /// Normally, you want to implement more sophisticated error handling,
47 /// and propagate errors upwards with `?` operator.
49 /// Even if you want to panic on errors, not all `Error`s implement good
50 /// messages on display. Therefore, it may be beneficial to look at the places
51 /// where they may get displayed. Activate this lint to do just that.
53 /// **Known problems:** None.
57 /// # let opt = Some(1);
63 /// opt.expect("more helpful message");
69 /// # let res: Result<usize, ()> = Ok(1);
75 /// res.expect("more helpful message");
79 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
82 declare_clippy_lint! {
83 /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
85 /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
86 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
87 /// this lint is `Allow` by default.
89 /// `result.expect()` will let the thread panic on `Err`
90 /// values. Normally, you want to implement more sophisticated error handling,
91 /// and propagate errors upwards with `?` operator.
93 /// **Known problems:** None.
97 /// # let opt = Some(1);
100 /// opt.expect("one");
103 /// let opt = Some(1);
110 /// # let res: Result<usize, ()> = Ok(1);
113 /// res.expect("one");
117 /// # Ok::<(), ()>(())
121 "using `.expect()` on `Result` or `Option`, which might be better handled"
124 declare_clippy_lint! {
125 /// **What it does:** Checks for methods that should live in a trait
126 /// implementation of a `std` trait (see [llogiq's blog
127 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
128 /// information) instead of an inherent implementation.
130 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
131 /// the code, often with very little cost. Also people seeing a `mul(...)`
133 /// may expect `*` to work equally, so you should have good reason to disappoint
136 /// **Known problems:** None.
142 /// fn add(&self, other: &X) -> X {
148 pub SHOULD_IMPLEMENT_TRAIT,
150 "defining a method that should be implementing a std trait"
153 declare_clippy_lint! {
154 /// **What it does:** Checks for methods with certain name prefixes and which
155 /// doesn't match how self is taken. The actual rules are:
157 /// |Prefix |`self` taken |
158 /// |-------|----------------------|
159 /// |`as_` |`&self` or `&mut self`|
161 /// |`into_`|`self` |
162 /// |`is_` |`&self` or none |
163 /// |`to_` |`&self` |
165 /// **Why is this bad?** Consistency breeds readability. If you follow the
166 /// conventions, your users won't be surprised that they, e.g., need to supply a
167 /// mutable reference to a `as_..` function.
169 /// **Known problems:** None.
175 /// fn as_str(self) -> &'static str {
181 pub WRONG_SELF_CONVENTION,
183 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
186 declare_clippy_lint! {
187 /// **What it does:** This is the same as
188 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
190 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
192 /// **Known problems:** Actually *renaming* the function may break clients if
193 /// the function is part of the public interface. In that case, be mindful of
194 /// the stability guarantees you've given your users.
200 /// pub fn as_str(self) -> &'a str {
205 pub WRONG_PUB_SELF_CONVENTION,
207 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
210 declare_clippy_lint! {
211 /// **What it does:** Checks for usage of `ok().expect(..)`.
213 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
214 /// directly to get a better error message.
216 /// **Known problems:** The error type needs to implement `Debug`
220 /// # let x = Ok::<_, ()>(());
223 /// x.ok().expect("why did I do this again?");
226 /// x.expect("why did I do this again?");
230 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
233 declare_clippy_lint! {
234 /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
235 /// `result.map(_).unwrap_or_else(_)`.
237 /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
238 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
240 /// **Known problems:** The order of the arguments is not in execution order
244 /// # let x = Some(1);
247 /// x.map(|a| a + 1).unwrap_or(0);
250 /// x.map_or(0, |a| a + 1);
256 /// # let x: Result<usize, ()> = Ok(1);
257 /// # fn some_function(foo: ()) -> usize { 1 }
260 /// x.map(|a| a + 1).unwrap_or_else(some_function);
263 /// x.map_or_else(some_function, |a| a + 1);
267 "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)`"
270 declare_clippy_lint! {
271 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
273 /// **Why is this bad?** Readability, this can be written more concisely as
276 /// **Known problems:** The order of the arguments is not in execution order.
280 /// # let opt = Some(1);
283 /// opt.map_or(None, |a| Some(a + 1));
286 /// opt.and_then(|a| Some(a + 1));
288 pub OPTION_MAP_OR_NONE,
290 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
293 declare_clippy_lint! {
294 /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
296 /// **Why is this bad?** Readability, this can be written more concisely as
299 /// **Known problems:** None.
305 /// # let r: Result<u32, &str> = Ok(1);
306 /// assert_eq!(Some(1), r.map_or(None, Some));
311 /// # let r: Result<u32, &str> = Ok(1);
312 /// assert_eq!(Some(1), r.ok());
314 pub RESULT_MAP_OR_INTO_OPTION,
316 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
319 declare_clippy_lint! {
320 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
321 /// `_.or_else(|x| Err(y))`.
323 /// **Why is this bad?** Readability, this can be written more concisely as
324 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
326 /// **Known problems:** None
331 /// # fn opt() -> Option<&'static str> { Some("42") }
332 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
333 /// let _ = opt().and_then(|s| Some(s.len()));
334 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
335 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
338 /// The correct use would be:
341 /// # fn opt() -> Option<&'static str> { Some("42") }
342 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
343 /// let _ = opt().map(|s| s.len());
344 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
345 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
347 pub BIND_INSTEAD_OF_MAP,
349 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
352 declare_clippy_lint! {
353 /// **What it does:** Checks for usage of `_.filter(_).next()`.
355 /// **Why is this bad?** Readability, this can be written more concisely as
358 /// **Known problems:** None.
362 /// # let vec = vec![1];
363 /// vec.iter().filter(|x| **x == 0).next();
365 /// Could be written as
367 /// # let vec = vec![1];
368 /// vec.iter().find(|x| **x == 0);
372 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
375 declare_clippy_lint! {
376 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
378 /// **Why is this bad?** Readability, this can be written more concisely as
379 /// `_.find(!condition)`.
381 /// **Known problems:** None.
385 /// # let vec = vec![1];
386 /// vec.iter().skip_while(|x| **x == 0).next();
388 /// Could be written as
390 /// # let vec = vec![1];
391 /// vec.iter().find(|x| **x != 0);
395 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
398 declare_clippy_lint! {
399 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
401 /// **Why is this bad?** Readability, this can be written more concisely as a
402 /// single method call using `_.flat_map(_)`
404 /// **Known problems:**
408 /// let vec = vec![vec![1]];
411 /// vec.iter().map(|x| x.iter()).flatten();
414 /// vec.iter().flat_map(|x| x.iter());
418 "using combinations of `flatten` and `map` which can usually be written as a single method call"
421 declare_clippy_lint! {
422 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
423 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
425 /// **Why is this bad?** Readability, this can be written more concisely as a
426 /// single method call.
428 /// **Known problems:** Often requires a condition + Option/Iterator creation
429 /// inside the closure.
433 /// let vec = vec![1];
436 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
439 /// vec.iter().filter_map(|x| if *x == 0 {
447 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
450 declare_clippy_lint! {
451 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
453 /// **Why is this bad?** Readability, this can be written more concisely as a
454 /// single method call.
456 /// **Known problems:** None
460 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
462 /// Can be written as
465 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
469 "using combination of `filter_map` and `next` which can usually be written as a single method call"
472 declare_clippy_lint! {
473 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
475 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
477 /// **Known problems:** None
481 /// # let iter = vec![vec![0]].into_iter();
482 /// iter.flat_map(|x| x);
484 /// Can be written as
486 /// # let iter = vec![vec![0]].into_iter();
489 pub FLAT_MAP_IDENTITY,
491 "call to `flat_map` where `flatten` is sufficient"
494 declare_clippy_lint! {
495 /// **What it does:** Checks for usage of `_.find(_).map(_)`.
497 /// **Why is this bad?** Readability, this can be written more concisely as a
498 /// single method call.
500 /// **Known problems:** Often requires a condition + Option/Iterator creation
501 /// inside the closure.
505 /// (0..3).find(|x| *x == 2).map(|x| x * 2);
507 /// Can be written as
509 /// (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
513 "using a combination of `find` and `map` can usually be written as a single method call"
516 declare_clippy_lint! {
517 /// **What it does:** Checks for an iterator search (such as `find()`,
518 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
520 /// **Why is this bad?** Readability, this can be written more concisely as
523 /// **Known problems:** None.
527 /// # let vec = vec![1];
528 /// vec.iter().find(|x| **x == 0).is_some();
530 /// Could be written as
532 /// # let vec = vec![1];
533 /// vec.iter().any(|x| *x == 0);
537 "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
540 declare_clippy_lint! {
541 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
542 /// if it starts with a given char.
544 /// **Why is this bad?** Readability, this can be written more concisely as
545 /// `_.starts_with(_)`.
547 /// **Known problems:** None.
551 /// let name = "foo";
552 /// if name.chars().next() == Some('_') {};
554 /// Could be written as
556 /// let name = "foo";
557 /// if name.starts_with('_') {};
561 "using `.chars().next()` to check if a string starts with a char"
564 declare_clippy_lint! {
565 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
566 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
567 /// `unwrap_or_default` instead.
569 /// **Why is this bad?** The function will always be called and potentially
570 /// allocate an object acting as the default.
572 /// **Known problems:** If the function has side-effects, not calling it will
573 /// change the semantic of the program, but you shouldn't rely on that anyway.
577 /// # let foo = Some(String::new());
578 /// foo.unwrap_or(String::new());
580 /// this can instead be written:
582 /// # let foo = Some(String::new());
583 /// foo.unwrap_or_else(String::new);
587 /// # let foo = Some(String::new());
588 /// foo.unwrap_or_default();
592 "using any `*or` method with a function call, which suggests `*or_else`"
595 declare_clippy_lint! {
596 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
597 /// etc., and suggests to use `unwrap_or_else` instead
599 /// **Why is this bad?** The function will always be called.
601 /// **Known problems:** If the function has side-effects, not calling it will
602 /// change the semantics of the program, but you shouldn't rely on that anyway.
606 /// # let foo = Some(String::new());
607 /// # let err_code = "418";
608 /// # let err_msg = "I'm a teapot";
609 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
613 /// # let foo = Some(String::new());
614 /// # let err_code = "418";
615 /// # let err_msg = "I'm a teapot";
616 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
618 /// this can instead be written:
620 /// # let foo = Some(String::new());
621 /// # let err_code = "418";
622 /// # let err_msg = "I'm a teapot";
623 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
627 "using any `expect` method with a function call"
630 declare_clippy_lint! {
631 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
633 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
634 /// generics, not for using the `clone` method on a concrete type.
636 /// **Known problems:** None.
644 "using `clone` on a `Copy` type"
647 declare_clippy_lint! {
648 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
649 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
650 /// function syntax instead (e.g., `Rc::clone(foo)`).
652 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
653 /// can obscure the fact that only the pointer is being cloned, not the underlying
658 /// # use std::rc::Rc;
659 /// let x = Rc::new(1);
667 pub CLONE_ON_REF_PTR,
669 "using 'clone' on a ref-counted pointer"
672 declare_clippy_lint! {
673 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
675 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
676 /// cloning the underlying `T`.
678 /// **Known problems:** None.
685 /// let z = y.clone();
686 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
689 pub CLONE_DOUBLE_REF,
691 "using `clone` on `&&T`"
694 declare_clippy_lint! {
695 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
696 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
698 /// **Why is this bad?** This bypasses the specialized implementation of
699 /// `ToString` and instead goes through the more expensive string formatting
702 /// **Known problems:** None.
706 /// // Generic implementation for `T: Display` is used (slow)
707 /// ["foo", "bar"].iter().map(|s| s.to_string());
709 /// // OK, the specialized impl is used
710 /// ["foo", "bar"].iter().map(|&s| s.to_string());
712 pub INEFFICIENT_TO_STRING,
714 "using `to_string` on `&&T` where `T: ToString`"
717 declare_clippy_lint! {
718 /// **What it does:** Checks for `new` not returning a type that contains `Self`.
720 /// **Why is this bad?** As a convention, `new` methods are used to make a new
721 /// instance of a type.
723 /// **Known problems:** None.
728 /// # struct NotAFoo;
730 /// fn new() -> NotAFoo {
738 /// # struct FooError;
740 /// // Good. Return type contains `Self`
741 /// fn new() -> Result<Foo, FooError> {
751 /// // Bad. The type name must contain `Self`.
752 /// fn new() -> Bar {
759 "not returning type containing `Self` in a `new` method"
762 declare_clippy_lint! {
763 /// **What it does:** Checks for string methods that receive a single-character
764 /// `str` as an argument, e.g., `_.split("x")`.
766 /// **Why is this bad?** Performing these methods using a `char` is faster than
769 /// **Known problems:** Does not catch multi-byte unicode characters.
778 pub SINGLE_CHAR_PATTERN,
780 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
783 declare_clippy_lint! {
784 /// **What it does:** Checks for getting the inner pointer of a temporary
787 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
788 /// as the `CString` is alive.
790 /// **Known problems:** None.
794 /// # use std::ffi::CString;
795 /// # fn call_some_ffi_func(_: *const i8) {}
797 /// let c_str = CString::new("foo").unwrap().as_ptr();
799 /// call_some_ffi_func(c_str);
802 /// Here `c_str` point to a freed address. The correct use would be:
804 /// # use std::ffi::CString;
805 /// # fn call_some_ffi_func(_: *const i8) {}
807 /// let c_str = CString::new("foo").unwrap();
809 /// call_some_ffi_func(c_str.as_ptr());
812 pub TEMPORARY_CSTRING_AS_PTR,
814 "getting the inner pointer of a temporary `CString`"
817 declare_clippy_lint! {
818 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
820 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
821 /// actually intend to panic.
823 /// **Known problems:** None.
826 /// ```rust,should_panic
827 /// for x in (0..100).step_by(0) {
831 pub ITERATOR_STEP_BY_ZERO,
833 "using `Iterator::step_by(0)`, which will panic at runtime"
836 declare_clippy_lint! {
837 /// **What it does:** Checks for the use of `iter.nth(0)`.
839 /// **Why is this bad?** `iter.next()` is equivalent to
840 /// `iter.nth(0)`, as they both consume the next element,
841 /// but is more readable.
843 /// **Known problems:** None.
848 /// # use std::collections::HashSet;
850 /// # let mut s = HashSet::new();
852 /// let x = s.iter().nth(0);
855 /// # let mut s = HashSet::new();
857 /// let x = s.iter().next();
861 "replace `iter.nth(0)` with `iter.next()`"
864 declare_clippy_lint! {
865 /// **What it does:** Checks for use of `.iter().nth()` (and the related
866 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
868 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
871 /// **Known problems:** None.
875 /// let some_vec = vec![0, 1, 2, 3];
876 /// let bad_vec = some_vec.iter().nth(3);
877 /// let bad_slice = &some_vec[..].iter().nth(3);
879 /// The correct use would be:
881 /// let some_vec = vec![0, 1, 2, 3];
882 /// let bad_vec = some_vec.get(3);
883 /// let bad_slice = &some_vec[..].get(3);
887 "using `.iter().nth()` on a standard library type with O(1) element access"
890 declare_clippy_lint! {
891 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
893 /// **Why is this bad?** `.nth(x)` is cleaner
895 /// **Known problems:** None.
899 /// let some_vec = vec![0, 1, 2, 3];
900 /// let bad_vec = some_vec.iter().skip(3).next();
901 /// let bad_slice = &some_vec[..].iter().skip(3).next();
903 /// The correct use would be:
905 /// let some_vec = vec![0, 1, 2, 3];
906 /// let bad_vec = some_vec.iter().nth(3);
907 /// let bad_slice = &some_vec[..].iter().nth(3);
911 "using `.skip(x).next()` on an iterator"
914 declare_clippy_lint! {
915 /// **What it does:** Checks for use of `.get().unwrap()` (or
916 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
918 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
921 /// **Known problems:** Not a replacement for error handling: Using either
922 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
923 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
924 /// temporary placeholder for dealing with the `Option` type, then this does
925 /// not mitigate the need for error handling. If there is a chance that `.get()`
926 /// will be `None` in your program, then it is advisable that the `None` case
927 /// is handled in a future refactor instead of using `.unwrap()` or the Index
932 /// let mut some_vec = vec![0, 1, 2, 3];
933 /// let last = some_vec.get(3).unwrap();
934 /// *some_vec.get_mut(0).unwrap() = 1;
936 /// The correct use would be:
938 /// let mut some_vec = vec![0, 1, 2, 3];
939 /// let last = some_vec[3];
944 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
947 declare_clippy_lint! {
948 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
949 /// `&str` or `String`.
951 /// **Why is this bad?** `.push_str(s)` is clearer
953 /// **Known problems:** None.
958 /// let def = String::from("def");
959 /// let mut s = String::new();
960 /// s.extend(abc.chars());
961 /// s.extend(def.chars());
963 /// The correct use would be:
966 /// let def = String::from("def");
967 /// let mut s = String::new();
969 /// s.push_str(&def);
971 pub STRING_EXTEND_CHARS,
973 "using `x.extend(s.chars())` where s is a `&str` or `String`"
976 declare_clippy_lint! {
977 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
980 /// **Why is this bad?** `.to_vec()` is clearer
982 /// **Known problems:** None.
986 /// let s = [1, 2, 3, 4, 5];
987 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
989 /// The better use would be:
991 /// let s = [1, 2, 3, 4, 5];
992 /// let s2: Vec<isize> = s.to_vec();
994 pub ITER_CLONED_COLLECT,
996 "using `.cloned().collect()` on slice to create a `Vec`"
999 declare_clippy_lint! {
1000 /// **What it does:** Checks for usage of `_.chars().last()` or
1001 /// `_.chars().next_back()` on a `str` to check if it ends with a given char.
1003 /// **Why is this bad?** Readability, this can be written more concisely as
1004 /// `_.ends_with(_)`.
1006 /// **Known problems:** None.
1010 /// # let name = "_";
1013 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-');
1016 /// name.ends_with('_') || name.ends_with('-');
1020 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
1023 declare_clippy_lint! {
1024 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
1025 /// types before and after the call are the same.
1027 /// **Why is this bad?** The call is unnecessary.
1029 /// **Known problems:** None.
1033 /// # fn do_stuff(x: &[i32]) {}
1034 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1035 /// do_stuff(x.as_ref());
1037 /// The correct use would be:
1039 /// # fn do_stuff(x: &[i32]) {}
1040 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1045 "using `as_ref` where the types before and after the call are the same"
1048 declare_clippy_lint! {
1049 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1050 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1051 /// `sum` or `product`.
1053 /// **Why is this bad?** Readability.
1055 /// **Known problems:** None.
1059 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1061 /// This could be written as:
1063 /// let _ = (0..3).any(|x| x > 2);
1065 pub UNNECESSARY_FOLD,
1067 "using `fold` when a more succinct alternative exists"
1070 declare_clippy_lint! {
1071 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1072 /// More specifically it checks if the closure provided is only performing one of the
1073 /// filter or map operations and suggests the appropriate option.
1075 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1076 /// operation is being performed.
1078 /// **Known problems:** None
1082 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1084 /// // As there is no transformation of the argument this could be written as:
1085 /// let _ = (0..3).filter(|&x| x > 2);
1089 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1091 /// // As there is no conditional check on the argument this could be written as:
1092 /// let _ = (0..4).map(|x| x + 1);
1094 pub UNNECESSARY_FILTER_MAP,
1096 "using `filter_map` when a more succinct alternative exists"
1099 declare_clippy_lint! {
1100 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1103 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1104 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1105 /// `iter_mut` directly.
1107 /// **Known problems:** None
1113 /// let _ = (&vec![3, 4, 5]).into_iter();
1116 /// let _ = (&vec![3, 4, 5]).iter();
1118 pub INTO_ITER_ON_REF,
1120 "using `.into_iter()` on a reference"
1123 declare_clippy_lint! {
1124 /// **What it does:** Checks for calls to `map` followed by a `count`.
1126 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1127 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1128 /// drive the iterator to completion, you can just use `for_each` instead.
1130 /// **Known problems:** None
1135 /// let _ = (0..3).map(|x| x + 2).count();
1139 "suspicious usage of map"
1142 declare_clippy_lint! {
1143 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1145 /// **Why is this bad?** For most types, this is undefined behavior.
1147 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1148 /// of `MaybeUninit`. There may be other types that allow uninitialized
1149 /// data, but those are not yet rigorously defined.
1154 /// // Beware the UB
1155 /// use std::mem::MaybeUninit;
1157 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1160 /// Note that the following is OK:
1163 /// use std::mem::MaybeUninit;
1165 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1166 /// MaybeUninit::uninit().assume_init()
1169 pub UNINIT_ASSUMED_INIT,
1171 "`MaybeUninit::uninit().assume_init()`"
1174 declare_clippy_lint! {
1175 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1177 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1182 /// # let y: u32 = 0;
1183 /// # let x: u32 = 100;
1184 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1185 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1188 /// can be written using dedicated methods for saturating addition/subtraction as:
1191 /// # let y: u32 = 0;
1192 /// # let x: u32 = 100;
1193 /// let add = x.saturating_add(y);
1194 /// let sub = x.saturating_sub(y);
1196 pub MANUAL_SATURATING_ARITHMETIC,
1198 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1201 declare_clippy_lint! {
1202 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1203 /// zero-sized types
1205 /// **Why is this bad?** This is a no-op, and likely unintended
1207 /// **Known problems:** None
1211 /// unsafe { (&() as *const ()).offset(1) };
1215 "Check for offset calculations on raw pointers to zero-sized types"
1218 declare_clippy_lint! {
1219 /// **What it does:** Checks for `FileType::is_file()`.
1221 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1222 /// they are testing whether a path is something they can get bytes from. But
1223 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1224 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1230 /// let metadata = std::fs::metadata("foo.txt")?;
1231 /// let filetype = metadata.file_type();
1233 /// if filetype.is_file() {
1236 /// # Ok::<_, std::io::Error>(())
1240 /// should be written as:
1244 /// let metadata = std::fs::metadata("foo.txt")?;
1245 /// let filetype = metadata.file_type();
1247 /// if !filetype.is_dir() {
1250 /// # Ok::<_, std::io::Error>(())
1253 pub FILETYPE_IS_FILE,
1255 "`FileType::is_file` is not recommended to test for readable file type"
1258 declare_clippy_lint! {
1259 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1261 /// **Why is this bad?** Readability, this can be written more concisely as a
1262 /// single method call.
1264 /// **Known problems:** None.
1268 /// # let opt = Some("".to_string());
1269 /// opt.as_ref().map(String::as_str)
1272 /// Can be written as
1274 /// # let opt = Some("".to_string());
1278 pub OPTION_AS_REF_DEREF,
1280 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1283 declare_clippy_lint! {
1284 /// **What it does:** Checks for usage of `iter().next()` on a Slice or an Array
1286 /// **Why is this bad?** These can be shortened into `.get()`
1288 /// **Known problems:** None.
1292 /// # let a = [1, 2, 3];
1293 /// # let b = vec![1, 2, 3];
1294 /// a[2..].iter().next();
1295 /// b.iter().next();
1297 /// should be written as:
1299 /// # let a = [1, 2, 3];
1300 /// # let b = vec![1, 2, 3];
1304 pub ITER_NEXT_SLICE,
1306 "using `.iter().next()` on a sliced array, which can be shortened to just `.get()`"
1309 declare_lint_pass!(Methods => [
1312 SHOULD_IMPLEMENT_TRAIT,
1313 WRONG_SELF_CONVENTION,
1314 WRONG_PUB_SELF_CONVENTION,
1317 RESULT_MAP_OR_INTO_OPTION,
1319 BIND_INSTEAD_OF_MAP,
1327 INEFFICIENT_TO_STRING,
1329 SINGLE_CHAR_PATTERN,
1331 TEMPORARY_CSTRING_AS_PTR,
1339 ITERATOR_STEP_BY_ZERO,
1345 STRING_EXTEND_CHARS,
1346 ITER_CLONED_COLLECT,
1349 UNNECESSARY_FILTER_MAP,
1352 UNINIT_ASSUMED_INIT,
1353 MANUAL_SATURATING_ARITHMETIC,
1356 OPTION_AS_REF_DEREF,
1359 impl<'tcx> LateLintPass<'tcx> for Methods {
1360 #[allow(clippy::too_many_lines)]
1361 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1362 if in_macro(expr.span) {
1366 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1367 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1368 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1370 match method_names.as_slice() {
1371 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1372 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1373 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1374 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1375 ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1376 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1377 ["unwrap_or_else", "map"] => lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]),
1378 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1379 ["and_then", ..] => {
1380 bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
1381 bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
1383 ["or_else", ..] => {
1384 bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]);
1386 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1387 ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1388 ["next", "iter"] => lint_iter_next(cx, expr, arg_lists[1]),
1389 ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
1390 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1391 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
1392 ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
1393 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1394 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1395 ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1396 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1397 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1398 ["is_some", "position"] => {
1399 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1401 ["is_some", "rposition"] => {
1402 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1404 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1405 ["as_ptr", "unwrap" | "expect"] => lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0]),
1406 ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1407 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1408 ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1409 ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1410 ["next", "skip"] => lint_iter_skip_next(cx, expr, arg_lists[1]),
1411 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1412 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1413 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1414 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1415 ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
1416 ["count", "map"] => lint_suspicious_map(cx, expr),
1417 ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1418 ["unwrap_or", arith @ ("checked_add" | "checked_sub" | "checked_mul")] => {
1419 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1421 ["add" | "offset" | "sub" | "wrapping_offset" | "wrapping_add" | "wrapping_sub"] => {
1422 check_pointer_offset(cx, expr, arg_lists[0])
1424 ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1425 ["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
1426 ["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
1431 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args, _) => {
1432 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1433 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1435 let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]);
1436 if args.len() == 1 && method_call.ident.name == sym!(clone) {
1437 lint_clone_on_copy(cx, expr, &args[0], self_ty);
1438 lint_clone_on_ref_ptr(cx, expr, &args[0]);
1440 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1441 inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1444 match self_ty.kind {
1445 ty::Ref(_, ty, _) if ty.kind == ty::Str => {
1446 for &(method, pos) in &PATTERN_METHODS {
1447 if method_call.ident.name.as_str() == method && args.len() > pos {
1448 lint_single_char_pattern(cx, expr, &args[pos]);
1452 ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
1453 lint_into_iter(cx, expr, self_ty, *method_span);
1458 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1459 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1461 let mut info = BinaryExprInfo {
1465 eq: op.node == hir::BinOpKind::Eq,
1467 lint_binary_expr_with_method_call(cx, &mut info);
1473 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1474 if in_external_macro(cx.sess(), impl_item.span) {
1477 let name = impl_item.ident.name.as_str();
1478 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
1479 let item = cx.tcx.hir().expect_item(parent);
1480 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1481 let self_ty = cx.tcx.type_of(def_id);
1483 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1484 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1485 if let hir::ItemKind::Impl{ of_trait: None, .. } = item.kind;
1487 let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
1488 let method_sig = cx.tcx.fn_sig(method_def_id);
1489 let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
1491 let first_arg_ty = &method_sig.inputs().iter().next();
1493 // check conventions w.r.t. conversion method names and predicates
1494 if let Some(first_arg_ty) = first_arg_ty;
1497 if cx.access_levels.is_exported(impl_item.hir_id) {
1498 // check missing trait implementations
1499 for &(method_name, n_args, fn_header, self_kind, out_type, trait_name) in &TRAIT_METHODS {
1500 if name == method_name &&
1501 sig.decl.inputs.len() == n_args &&
1502 out_type.matches(cx, &sig.decl.output) &&
1503 self_kind.matches(cx, self_ty, first_arg_ty) &&
1504 fn_header_equals(*fn_header, sig.header) {
1505 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, impl_item.span, &format!(
1506 "defining a method called `{}` on this type; consider implementing \
1507 the `{}` trait or choosing a less ambiguous name", name, trait_name));
1512 if let Some((ref conv, self_kinds)) = &CONVENTIONS
1514 .find(|(ref conv, _)| conv.check(&name))
1516 if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
1517 let lint = if item.vis.node.is_pub() {
1518 WRONG_PUB_SELF_CONVENTION
1520 WRONG_SELF_CONVENTION
1527 &format!("methods called `{}` usually take {}; consider choosing a less ambiguous name",
1531 .map(|k| k.description())
1532 .collect::<Vec<_>>()
1541 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1542 let ret_ty = return_ty(cx, impl_item.hir_id);
1544 let contains_self_ty = |ty: Ty<'tcx>| {
1545 ty.walk().any(|inner| match inner.unpack() {
1546 GenericArgKind::Type(inner_ty) => TyS::same_type(self_ty, inner_ty),
1548 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
1552 // walk the return type and check for Self (this does not check associated types)
1553 if contains_self_ty(ret_ty) {
1557 // if return type is impl trait, check the associated types
1558 if let ty::Opaque(def_id, _) = ret_ty.kind {
1559 // one of the associated types must be Self
1560 for &(predicate, _span) in cx.tcx.predicates_of(def_id).predicates {
1561 if let ty::PredicateAtom::Projection(projection_predicate) = predicate.skip_binders() {
1562 // walk the associated type and check for Self
1563 if contains_self_ty(projection_predicate.ty) {
1570 if name == "new" && !TyS::same_type(ret_ty, self_ty) {
1575 "methods called `new` usually return `Self`",
1582 /// Checks for the `OR_FUN_CALL` lint.
1583 #[allow(clippy::too_many_lines)]
1584 fn lint_or_fun_call<'tcx>(
1585 cx: &LateContext<'tcx>,
1586 expr: &hir::Expr<'_>,
1589 args: &'tcx [hir::Expr<'_>],
1591 // Searches an expression for method calls or function calls that aren't ctors
1592 struct FunCallFinder<'a, 'tcx> {
1593 cx: &'a LateContext<'tcx>,
1597 impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
1598 type Map = Map<'tcx>;
1600 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
1601 let call_found = match &expr.kind {
1602 // ignore enum and struct constructors
1603 hir::ExprKind::Call(..) => !is_ctor_or_promotable_const_function(self.cx, expr),
1604 hir::ExprKind::MethodCall(..) => true,
1613 intravisit::walk_expr(self, expr);
1617 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1618 intravisit::NestedVisitorMap::None
1622 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1623 fn check_unwrap_or_default(
1624 cx: &LateContext<'_>,
1626 fun: &hir::Expr<'_>,
1627 self_expr: &hir::Expr<'_>,
1628 arg: &hir::Expr<'_>,
1634 if name == "unwrap_or";
1635 if let hir::ExprKind::Path(ref qpath) = fun.kind;
1636 let path = &*last_path_segment(qpath).ident.as_str();
1637 if ["default", "new"].contains(&path);
1638 let arg_ty = cx.typeck_results().expr_ty(arg);
1639 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1640 if implements_trait(cx, arg_ty, default_trait_id, &[]);
1643 let mut applicability = Applicability::MachineApplicable;
1648 &format!("use of `{}` followed by a call to `{}`", name, path),
1651 "{}.unwrap_or_default()",
1652 snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
1664 /// Checks for `*or(foo())`.
1665 #[allow(clippy::too_many_arguments)]
1666 fn check_general_case<'tcx>(
1667 cx: &LateContext<'tcx>,
1671 self_expr: &hir::Expr<'_>,
1672 arg: &'tcx hir::Expr<'_>,
1676 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind {
1677 if path.ident.as_str() == "len" {
1678 let ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0]));
1681 ty::Slice(_) | ty::Array(_, _) => return,
1685 if match_type(cx, ty, &paths::VEC) {
1691 // (path, fn_has_argument, methods, suffix)
1692 let know_types: &[(&[_], _, &[_], _)] = &[
1693 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1694 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1695 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1696 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1700 if know_types.iter().any(|k| k.2.contains(&name));
1702 let mut finder = FunCallFinder { cx: &cx, found: false };
1703 if { finder.visit_expr(&arg); finder.found };
1704 if !contains_return(&arg);
1706 let self_ty = cx.typeck_results().expr_ty(self_expr);
1708 if let Some(&(_, fn_has_arguments, poss, suffix)) =
1709 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
1711 if poss.contains(&name);
1714 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1715 (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1716 (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1717 (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1719 let span_replace_word = method_span.with_hi(span.hi());
1724 &format!("use of `{}` followed by a function call", name),
1726 format!("{}_{}({})", name, suffix, sugg),
1727 Applicability::HasPlaceholders,
1733 if args.len() == 2 {
1734 match args[1].kind {
1735 hir::ExprKind::Call(ref fun, ref or_args) => {
1736 let or_has_args = !or_args.is_empty();
1737 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1750 hir::ExprKind::MethodCall(_, span, ref or_args, _) => check_general_case(
1757 !or_args.is_empty(),
1765 /// Checks for the `EXPECT_FUN_CALL` lint.
1766 #[allow(clippy::too_many_lines)]
1767 fn lint_expect_fun_call(
1768 cx: &LateContext<'_>,
1769 expr: &hir::Expr<'_>,
1772 args: &[hir::Expr<'_>],
1774 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1776 fn get_arg_root<'a>(cx: &LateContext<'_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1777 let mut arg_root = arg;
1779 arg_root = match &arg_root.kind {
1780 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1781 hir::ExprKind::MethodCall(method_name, _, call_args, _) => {
1782 if call_args.len() == 1
1783 && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1785 let arg_type = cx.typeck_results().expr_ty(&call_args[0]);
1786 let base_type = walk_ptrs_ty(arg_type);
1787 base_type.kind == ty::Str || is_type_diagnostic_item(cx, base_type, sym!(string_type))
1801 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1802 // converted to string.
1803 fn requires_to_string(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
1804 let arg_ty = cx.typeck_results().expr_ty(arg);
1805 if is_type_diagnostic_item(cx, arg_ty, sym!(string_type)) {
1808 if let ty::Ref(_, ty, ..) = arg_ty.kind {
1809 if ty.kind == ty::Str && can_be_static_str(cx, arg) {
1816 // Check if an expression could have type `&'static str`, knowing that it
1817 // has type `&str` for some lifetime.
1818 fn can_be_static_str(cx: &LateContext<'_>, arg: &hir::Expr<'_>) -> bool {
1820 hir::ExprKind::Lit(_) => true,
1821 hir::ExprKind::Call(fun, _) => {
1822 if let hir::ExprKind::Path(ref p) = fun.kind {
1823 match cx.qpath_res(p, fun.hir_id) {
1824 hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!(
1825 cx.tcx.fn_sig(def_id).output().skip_binder().kind,
1826 ty::Ref(ty::ReStatic, ..)
1834 hir::ExprKind::MethodCall(..) => {
1836 .type_dependent_def_id(arg.hir_id)
1837 .map_or(false, |method_id| {
1839 cx.tcx.fn_sig(method_id).output().skip_binder().kind,
1840 ty::Ref(ty::ReStatic, ..)
1844 hir::ExprKind::Path(ref p) => matches!(
1845 cx.qpath_res(p, arg.hir_id),
1846 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _)
1852 fn generate_format_arg_snippet(
1853 cx: &LateContext<'_>,
1855 applicability: &mut Applicability,
1858 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1859 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1860 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
1865 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1873 fn is_call(node: &hir::ExprKind<'_>) -> bool {
1875 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
1878 hir::ExprKind::Call(..)
1879 | hir::ExprKind::MethodCall(..)
1880 // These variants are debatable or require further examination
1881 | hir::ExprKind::Match(..)
1882 | hir::ExprKind::Block{ .. } => true,
1887 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
1891 let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]);
1892 let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym!(option_type)) {
1894 } else if is_type_diagnostic_item(cx, receiver_type, sym!(result_type)) {
1900 let arg_root = get_arg_root(cx, &args[1]);
1902 let span_replace_word = method_span.with_hi(expr.span.hi());
1904 let mut applicability = Applicability::MachineApplicable;
1906 //Special handling for `format!` as arg_root
1908 if let hir::ExprKind::Block(block, None) = &arg_root.kind;
1909 if block.stmts.len() == 1;
1910 if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
1911 if let Some(arg_root) = &local.init;
1912 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
1913 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
1914 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
1916 let fmt_spec = &format_args[0];
1917 let fmt_args = &format_args[1];
1919 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1921 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1923 let sugg = args.join(", ");
1929 &format!("use of `{}` followed by a function call", name),
1931 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1939 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1940 if requires_to_string(cx, arg_root) {
1941 arg_root_snippet.to_mut().push_str(".to_string()");
1948 &format!("use of `{}` followed by a function call", name),
1950 format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1955 /// Checks for the `CLONE_ON_COPY` lint.
1956 fn lint_clone_on_copy(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
1957 let ty = cx.typeck_results().expr_ty(expr);
1958 if let ty::Ref(_, inner, _) = arg_ty.kind {
1959 if let ty::Ref(_, innermost, _) = inner.kind {
1964 "using `clone` on a double-reference; \
1965 this will copy the reference instead of cloning the inner type",
1967 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1968 let mut ty = innermost;
1970 while let ty::Ref(_, inner, _) = ty.kind {
1974 let refs: String = iter::repeat('&').take(n + 1).collect();
1975 let derefs: String = iter::repeat('*').take(n).collect();
1976 let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
1977 diag.span_suggestion(
1979 "try dereferencing it",
1980 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1981 Applicability::MaybeIncorrect,
1983 diag.span_suggestion(
1985 "or try being explicit if you are sure, that you want to clone a reference",
1987 Applicability::MaybeIncorrect,
1992 return; // don't report clone_on_copy
1996 if is_copy(cx, ty) {
1998 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1999 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
2000 match &cx.tcx.hir().get(parent) {
2001 hir::Node::Expr(parent) => match parent.kind {
2002 // &*x is a nop, &x.clone() is not
2003 hir::ExprKind::AddrOf(..) => return,
2004 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
2005 hir::ExprKind::MethodCall(_, _, parent_args, _) if expr.hir_id == parent_args[0].hir_id => {
2011 hir::Node::Stmt(stmt) => {
2012 if let hir::StmtKind::Local(ref loc) = stmt.kind {
2013 if let hir::PatKind::Ref(..) = loc.pat.kind {
2014 // let ref y = *x borrows x, let ref y = x.clone() does not
2022 // x.clone() might have dereferenced x, possibly through Deref impls
2023 if cx.typeck_results().expr_ty(arg) == ty {
2024 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
2026 let deref_count = cx
2028 .expr_adjustments(arg)
2030 .filter(|adj| matches!(adj.kind, ty::adjustment::Adjust::Deref(_)))
2032 let derefs: String = iter::repeat('*').take(deref_count).collect();
2033 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
2038 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |diag| {
2039 if let Some((text, snip)) = snip {
2040 diag.span_suggestion(expr.span, text, snip, Applicability::MachineApplicable);
2046 fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
2047 let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(arg));
2049 if let ty::Adt(_, subst) = obj_ty.kind {
2050 let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
2052 } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
2054 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
2064 "using `.clone()` on a ref-counted pointer",
2067 "{}::<{}>::clone(&{})",
2070 snippet(cx, arg.span, "_")
2072 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
2077 fn lint_string_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2079 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2080 let target = &arglists[0][0];
2081 let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(target));
2082 let ref_str = if self_ty.kind == ty::Str {
2084 } else if is_type_diagnostic_item(cx, self_ty, sym!(string_type)) {
2090 let mut applicability = Applicability::MachineApplicable;
2093 STRING_EXTEND_CHARS,
2095 "calling `.extend(_.chars())`",
2098 "{}.push_str({}{})",
2099 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
2101 snippet_with_applicability(cx, target.span, "_", &mut applicability)
2108 fn lint_extend(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2109 let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0]));
2110 if is_type_diagnostic_item(cx, obj_ty, sym!(string_type)) {
2111 lint_string_extend(cx, expr, args);
2115 fn lint_cstring_as_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2117 let source_type = cx.typeck_results().expr_ty(source);
2118 if let ty::Adt(def, substs) = source_type.kind;
2119 if cx.tcx.is_diagnostic_item(sym!(result_type), def.did);
2120 if match_type(cx, substs.type_at(0), &paths::CSTRING);
2124 TEMPORARY_CSTRING_AS_PTR,
2126 "you are getting the inner pointer of a temporary `CString`",
2128 diag.note("that pointer will be invalid outside this expression");
2129 diag.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2135 fn lint_iter_cloned_collect<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2137 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym!(vec_type));
2138 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0]));
2139 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2144 ITER_CLONED_COLLECT,
2146 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2149 ".to_vec()".to_string(),
2150 Applicability::MachineApplicable,
2156 fn lint_unnecessary_fold(cx: &LateContext<'_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2157 fn check_fold_with_op(
2158 cx: &LateContext<'_>,
2159 expr: &hir::Expr<'_>,
2160 fold_args: &[hir::Expr<'_>],
2163 replacement_method_name: &str,
2164 replacement_has_args: bool,
2167 // Extract the body of the closure passed to fold
2168 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2169 let closure_body = cx.tcx.hir().body(body_id);
2170 let closure_expr = remove_blocks(&closure_body.value);
2172 // Check if the closure body is of the form `acc <op> some_expr(x)`
2173 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2174 if bin_op.node == op;
2176 // Extract the names of the two arguments to the closure
2177 if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2178 if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2180 if match_var(&*left_expr, first_arg_ident);
2181 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2184 let mut applicability = Applicability::MachineApplicable;
2185 let sugg = if replacement_has_args {
2187 "{replacement}(|{s}| {r})",
2188 replacement = replacement_method_name,
2189 s = second_arg_ident,
2190 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2195 replacement = replacement_method_name,
2202 fold_span.with_hi(expr.span.hi()),
2203 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2204 "this `.fold` can be written more succinctly using another method",
2213 // Check that this is a call to Iterator::fold rather than just some function called fold
2214 if !match_trait_method(cx, expr, &paths::ITERATOR) {
2219 fold_args.len() == 3,
2220 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2223 // Check if the first argument to .fold is a suitable literal
2224 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2226 ast::LitKind::Bool(false) => {
2227 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2229 ast::LitKind::Bool(true) => {
2230 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2232 ast::LitKind::Int(0, _) => {
2233 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2235 ast::LitKind::Int(1, _) => {
2236 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2243 fn lint_step_by<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2244 if match_trait_method(cx, expr, &paths::ITERATOR) {
2245 if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &args[1]) {
2248 ITERATOR_STEP_BY_ZERO,
2250 "Iterator::step_by(0) will panic at runtime",
2256 fn lint_iter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, iter_args: &'tcx [hir::Expr<'_>]) {
2257 let caller_expr = &iter_args[0];
2259 // Skip lint if the `iter().next()` expression is a for loop argument,
2260 // since it is already covered by `&loops::ITER_NEXT_LOOP`
2261 let mut parent_expr_opt = get_parent_expr(cx, expr);
2262 while let Some(parent_expr) = parent_expr_opt {
2263 if higher::for_loop(parent_expr).is_some() {
2266 parent_expr_opt = get_parent_expr(cx, parent_expr);
2269 if derefs_to_slice(cx, caller_expr, cx.typeck_results().expr_ty(caller_expr)).is_some() {
2270 // caller is a Slice
2272 if let hir::ExprKind::Index(ref caller_var, ref index_expr) = &caller_expr.kind;
2273 if let Some(higher::Range { start: Some(start_expr), end: None, limits: ast::RangeLimits::HalfOpen })
2274 = higher::range(cx, index_expr);
2275 if let hir::ExprKind::Lit(ref start_lit) = &start_expr.kind;
2276 if let ast::LitKind::Int(start_idx, _) = start_lit.node;
2278 let mut applicability = Applicability::MachineApplicable;
2283 "Using `.iter().next()` on a Slice without end index.",
2285 format!("{}.get({})", snippet_with_applicability(cx, caller_var.span, "..", &mut applicability), start_idx),
2290 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(caller_expr), sym!(vec_type))
2292 &walk_ptrs_ty(cx.typeck_results().expr_ty(caller_expr)).kind,
2296 // caller is a Vec or an Array
2297 let mut applicability = Applicability::MachineApplicable;
2302 "Using `.iter().next()` on an array",
2306 snippet_with_applicability(cx, caller_expr.span, "..", &mut applicability)
2313 fn lint_iter_nth<'tcx>(
2314 cx: &LateContext<'tcx>,
2315 expr: &hir::Expr<'_>,
2316 nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2319 let iter_args = nth_and_iter_args[1];
2320 let mut_str = if is_mut { "_mut" } else { "" };
2321 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])).is_some() {
2323 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vec_type)) {
2325 } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vecdeque_type)) {
2328 let nth_args = nth_and_iter_args[0];
2329 lint_iter_nth_zero(cx, expr, &nth_args);
2330 return; // caller is not a type that we want to lint
2337 &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2339 &format!("calling `.get{}()` is both faster and more readable", mut_str),
2343 fn lint_iter_nth_zero<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2345 if match_trait_method(cx, expr, &paths::ITERATOR);
2346 if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &nth_args[1]);
2348 let mut applicability = Applicability::MachineApplicable;
2353 "called `.nth(0)` on a `std::iter::Iterator`, when `.next()` is equivalent",
2354 "try calling `.next()` instead of `.nth(0)`",
2355 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2362 fn lint_get_unwrap<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, get_args: &'tcx [hir::Expr<'_>], is_mut: bool) {
2363 // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2364 // because they do not implement `IndexMut`
2365 let mut applicability = Applicability::MachineApplicable;
2366 let expr_ty = cx.typeck_results().expr_ty(&get_args[0]);
2367 let get_args_str = if get_args.len() > 1 {
2368 snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
2370 return; // not linting on a .get().unwrap() chain or variant
2373 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2374 needs_ref = get_args_str.parse::<usize>().is_ok();
2376 } else if is_type_diagnostic_item(cx, expr_ty, sym!(vec_type)) {
2377 needs_ref = get_args_str.parse::<usize>().is_ok();
2379 } else if is_type_diagnostic_item(cx, expr_ty, sym!(vecdeque_type)) {
2380 needs_ref = get_args_str.parse::<usize>().is_ok();
2382 } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym!(hashmap_type)) {
2385 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2389 return; // caller is not a type that we want to lint
2392 let mut span = expr.span;
2394 // Handle the case where the result is immediately dereferenced
2395 // by not requiring ref and pulling the dereference into the
2399 if let Some(parent) = get_parent_expr(cx, expr);
2400 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2407 let mut_str = if is_mut { "_mut" } else { "" };
2408 let borrow_str = if !needs_ref {
2421 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2422 mut_str, caller_type
2428 snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
2435 fn lint_iter_skip_next(cx: &LateContext<'_>, expr: &hir::Expr<'_>, skip_args: &[hir::Expr<'_>]) {
2436 // lint if caller of skip is an Iterator
2437 if match_trait_method(cx, expr, &paths::ITERATOR) {
2438 if let [caller, n] = skip_args {
2439 let hint = format!(".nth({})", snippet(cx, n.span, ".."));
2443 expr.span.trim_start(caller.span).unwrap(),
2444 "called `skip(x).next()` on an iterator",
2445 "use `nth` instead",
2447 Applicability::MachineApplicable,
2453 fn derefs_to_slice<'tcx>(
2454 cx: &LateContext<'tcx>,
2455 expr: &'tcx hir::Expr<'tcx>,
2457 ) -> Option<&'tcx hir::Expr<'tcx>> {
2458 fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
2460 ty::Slice(_) => true,
2461 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2462 ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym!(vec_type)),
2463 ty::Array(_, size) => size
2464 .try_eval_usize(cx.tcx, cx.param_env)
2465 .map_or(false, |size| size < 32),
2466 ty::Ref(_, inner, _) => may_slice(cx, inner),
2471 if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
2472 if path.ident.name == sym!(iter) && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
2479 ty::Slice(_) => Some(expr),
2480 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2481 ty::Ref(_, inner, _) => {
2482 if may_slice(cx, inner) {
2493 /// lint use of `unwrap()` for `Option`s and `Result`s
2494 fn lint_unwrap(cx: &LateContext<'_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2495 let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&unwrap_args[0]));
2497 let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2498 Some((UNWRAP_USED, "an Option", "None"))
2499 } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2500 Some((UNWRAP_USED, "a Result", "Err"))
2505 if let Some((lint, kind, none_value)) = mess {
2510 &format!("used `unwrap()` on `{}` value", kind,),
2513 "if you don't want to handle the `{}` case gracefully, consider \
2514 using `expect()` to provide a better panic message",
2521 /// lint use of `expect()` for `Option`s and `Result`s
2522 fn lint_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2523 let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&expect_args[0]));
2525 let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2526 Some((EXPECT_USED, "an Option", "None"))
2527 } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2528 Some((EXPECT_USED, "a Result", "Err"))
2533 if let Some((lint, kind, none_value)) = mess {
2538 &format!("used `expect()` on `{}` value", kind,),
2540 &format!("if this value is an `{}`, it will panic", none_value,),
2545 /// lint use of `ok().expect()` for `Result`s
2546 fn lint_ok_expect(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2548 // lint if the caller of `ok()` is a `Result`
2549 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&ok_args[0]), sym!(result_type));
2550 let result_type = cx.typeck_results().expr_ty(&ok_args[0]);
2551 if let Some(error_type) = get_error_type(cx, result_type);
2552 if has_debug_impl(error_type, cx);
2559 "called `ok().expect()` on a `Result` value",
2561 "you can call `expect()` directly on the `Result`",
2567 /// lint use of `map().flatten()` for `Iterators` and 'Options'
2568 fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2569 // lint if caller of `.map().flatten()` is an Iterator
2570 if match_trait_method(cx, expr, &paths::ITERATOR) {
2571 let map_closure_ty = cx.typeck_results().expr_ty(&map_args[1]);
2572 let is_map_to_option = match map_closure_ty.kind {
2573 ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => {
2574 let map_closure_sig = match map_closure_ty.kind {
2575 ty::Closure(_, substs) => substs.as_closure().sig(),
2576 _ => map_closure_ty.fn_sig(cx.tcx),
2578 let map_closure_return_ty = cx.tcx.erase_late_bound_regions(&map_closure_sig.output());
2579 is_type_diagnostic_item(cx, map_closure_return_ty, sym!(option_type))
2584 let method_to_use = if is_map_to_option {
2585 // `(...).map(...)` has type `impl Iterator<Item=Option<...>>
2588 // `(...).map(...)` has type `impl Iterator<Item=impl Iterator<...>>
2591 let func_snippet = snippet(cx, map_args[1].span, "..");
2592 let hint = format!(".{0}({1})", method_to_use, func_snippet);
2596 expr.span.with_lo(map_args[0].span.hi()),
2597 "called `map(..).flatten()` on an `Iterator`",
2598 &format!("try using `{}` instead", method_to_use),
2600 Applicability::MachineApplicable,
2604 // lint if caller of `.map().flatten()` is an Option
2605 if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type)) {
2606 let func_snippet = snippet(cx, map_args[1].span, "..");
2607 let hint = format!(".and_then({})", func_snippet);
2611 expr.span.with_lo(map_args[0].span.hi()),
2612 "called `map(..).flatten()` on an `Option`",
2613 "try using `and_then` instead",
2615 Applicability::MachineApplicable,
2620 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2621 fn lint_map_unwrap_or_else<'tcx>(
2622 cx: &LateContext<'tcx>,
2623 expr: &'tcx hir::Expr<'_>,
2624 map_args: &'tcx [hir::Expr<'_>],
2625 unwrap_args: &'tcx [hir::Expr<'_>],
2627 // lint if the caller of `map()` is an `Option`
2628 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type));
2629 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(result_type));
2631 if is_option || is_result {
2632 // Don't make a suggestion that may fail to compile due to mutably borrowing
2633 // the same variable twice.
2634 let map_mutated_vars = mutated_variables(&map_args[0], cx);
2635 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2636 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2637 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2645 let msg = if is_option {
2646 "called `map(f).unwrap_or_else(g)` on an `Option` value. This can be done more directly by calling \
2647 `map_or_else(g, f)` instead"
2649 "called `map(f).unwrap_or_else(g)` on a `Result` value. This can be done more directly by calling \
2650 `.map_or_else(g, f)` instead"
2652 // get snippets for args to map() and unwrap_or_else()
2653 let map_snippet = snippet(cx, map_args[1].span, "..");
2654 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2655 // lint, with note if neither arg is > 1 line and both map() and
2656 // unwrap_or_else() have the same span
2657 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2658 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2659 if same_span && !multiline {
2667 "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
2668 map_snippet, unwrap_snippet,
2671 } else if same_span && multiline {
2672 span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
2677 /// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
2678 fn lint_map_or_none<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>]) {
2679 let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym!(option_type));
2680 let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym!(result_type));
2682 // There are two variants of this `map_or` lint:
2683 // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
2684 // (2) using `map_or` as a combinator instead of `and_then`
2686 // (For this lint) we don't care if any other type calls `map_or`
2687 if !is_option && !is_result {
2691 let (lint_name, msg, instead, hint) = {
2692 let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2693 match_qpath(qpath, &paths::OPTION_NONE)
2698 if !default_arg_is_none {
2703 let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
2704 match_qpath(qpath, &paths::OPTION_SOME)
2710 let self_snippet = snippet(cx, map_or_args[0].span, "..");
2711 let func_snippet = snippet(cx, map_or_args[2].span, "..");
2712 let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \
2713 `and_then(f)` instead";
2717 "try using `and_then` instead",
2718 format!("{0}.and_then({1})", self_snippet, func_snippet),
2720 } else if f_arg_is_some {
2721 let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
2723 let self_snippet = snippet(cx, map_or_args[0].span, "..");
2725 RESULT_MAP_OR_INTO_OPTION,
2727 "try using `ok` instead",
2728 format!("{0}.ok()", self_snippet),
2743 Applicability::MachineApplicable,
2747 /// lint use of `filter().next()` for `Iterators`
2748 fn lint_filter_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
2749 // lint if caller of `.filter().next()` is an Iterator
2750 if match_trait_method(cx, expr, &paths::ITERATOR) {
2751 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2752 `.find(p)` instead.";
2753 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2754 if filter_snippet.lines().count() <= 1 {
2755 // add note if not multi-line
2762 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2765 span_lint(cx, FILTER_NEXT, expr.span, msg);
2770 /// lint use of `skip_while().next()` for `Iterators`
2771 fn lint_skip_while_next<'tcx>(
2772 cx: &LateContext<'tcx>,
2773 expr: &'tcx hir::Expr<'_>,
2774 _skip_while_args: &'tcx [hir::Expr<'_>],
2776 // lint if caller of `.skip_while().next()` is an Iterator
2777 if match_trait_method(cx, expr, &paths::ITERATOR) {
2782 "called `skip_while(p).next()` on an `Iterator`",
2784 "this is more succinctly expressed by calling `.find(!p)` instead",
2789 /// lint use of `filter().map()` for `Iterators`
2790 fn lint_filter_map<'tcx>(
2791 cx: &LateContext<'tcx>,
2792 expr: &'tcx hir::Expr<'_>,
2793 _filter_args: &'tcx [hir::Expr<'_>],
2794 _map_args: &'tcx [hir::Expr<'_>],
2796 // lint if caller of `.filter().map()` is an Iterator
2797 if match_trait_method(cx, expr, &paths::ITERATOR) {
2798 let msg = "called `filter(p).map(q)` on an `Iterator`";
2799 let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2800 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2804 /// lint use of `filter_map().next()` for `Iterators`
2805 fn lint_filter_map_next<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, filter_args: &'tcx [hir::Expr<'_>]) {
2806 if match_trait_method(cx, expr, &paths::ITERATOR) {
2807 let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2808 `.find_map(p)` instead.";
2809 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2810 if filter_snippet.lines().count() <= 1 {
2817 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2820 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2825 /// lint use of `find().map()` for `Iterators`
2826 fn lint_find_map<'tcx>(
2827 cx: &LateContext<'tcx>,
2828 expr: &'tcx hir::Expr<'_>,
2829 _find_args: &'tcx [hir::Expr<'_>],
2830 map_args: &'tcx [hir::Expr<'_>],
2832 // lint if caller of `.filter().map()` is an Iterator
2833 if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2834 let msg = "called `find(p).map(q)` on an `Iterator`";
2835 let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2836 span_lint_and_help(cx, FIND_MAP, expr.span, msg, None, hint);
2840 /// lint use of `filter_map().map()` for `Iterators`
2841 fn lint_filter_map_map<'tcx>(
2842 cx: &LateContext<'tcx>,
2843 expr: &'tcx hir::Expr<'_>,
2844 _filter_args: &'tcx [hir::Expr<'_>],
2845 _map_args: &'tcx [hir::Expr<'_>],
2847 // lint if caller of `.filter().map()` is an Iterator
2848 if match_trait_method(cx, expr, &paths::ITERATOR) {
2849 let msg = "called `filter_map(p).map(q)` on an `Iterator`";
2850 let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2851 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2855 /// lint use of `filter().flat_map()` for `Iterators`
2856 fn lint_filter_flat_map<'tcx>(
2857 cx: &LateContext<'tcx>,
2858 expr: &'tcx hir::Expr<'_>,
2859 _filter_args: &'tcx [hir::Expr<'_>],
2860 _map_args: &'tcx [hir::Expr<'_>],
2862 // lint if caller of `.filter().flat_map()` is an Iterator
2863 if match_trait_method(cx, expr, &paths::ITERATOR) {
2864 let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
2865 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2866 and filtering by returning `iter::empty()`";
2867 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2871 /// lint use of `filter_map().flat_map()` for `Iterators`
2872 fn lint_filter_map_flat_map<'tcx>(
2873 cx: &LateContext<'tcx>,
2874 expr: &'tcx hir::Expr<'_>,
2875 _filter_args: &'tcx [hir::Expr<'_>],
2876 _map_args: &'tcx [hir::Expr<'_>],
2878 // lint if caller of `.filter_map().flat_map()` is an Iterator
2879 if match_trait_method(cx, expr, &paths::ITERATOR) {
2880 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
2881 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2882 and filtering by returning `iter::empty()`";
2883 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2887 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2888 fn lint_flat_map_identity<'tcx>(
2889 cx: &LateContext<'tcx>,
2890 expr: &'tcx hir::Expr<'_>,
2891 flat_map_args: &'tcx [hir::Expr<'_>],
2892 flat_map_span: Span,
2894 if match_trait_method(cx, expr, &paths::ITERATOR) {
2895 let arg_node = &flat_map_args[1].kind;
2897 let apply_lint = |message: &str| {
2901 flat_map_span.with_hi(expr.span.hi()),
2904 "flatten()".to_string(),
2905 Applicability::MachineApplicable,
2910 if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
2911 let body = cx.tcx.hir().body(*body_id);
2913 if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
2914 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
2916 if path.segments.len() == 1;
2917 if path.segments[0].ident.as_str() == binding_ident.as_str();
2920 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
2925 if let hir::ExprKind::Path(ref qpath) = arg_node;
2927 if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2930 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
2936 /// lint searching an Iterator followed by `is_some()`
2937 fn lint_search_is_some<'tcx>(
2938 cx: &LateContext<'tcx>,
2939 expr: &'tcx hir::Expr<'_>,
2940 search_method: &str,
2941 search_args: &'tcx [hir::Expr<'_>],
2942 is_some_args: &'tcx [hir::Expr<'_>],
2945 // lint if caller of search is an Iterator
2946 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2948 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2949 expressed by calling `any()`.",
2952 let search_snippet = snippet(cx, search_args[1].span, "..");
2953 if search_snippet.lines().count() <= 1 {
2954 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2955 // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
2956 let any_search_snippet = if_chain! {
2957 if search_method == "find";
2958 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
2959 let closure_body = cx.tcx.hir().body(body_id);
2960 if let Some(closure_arg) = closure_body.params.get(0);
2962 if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
2963 Some(search_snippet.replacen('&', "", 1))
2964 } else if let Some(name) = get_arg_name(&closure_arg.pat) {
2965 Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
2973 // add note if not multi-line
2977 method_span.with_hi(expr.span.hi()),
2982 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2984 Applicability::MachineApplicable,
2987 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2992 /// Used for `lint_binary_expr_with_method_call`.
2993 #[derive(Copy, Clone)]
2994 struct BinaryExprInfo<'a> {
2995 expr: &'a hir::Expr<'a>,
2996 chain: &'a hir::Expr<'a>,
2997 other: &'a hir::Expr<'a>,
3001 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3002 fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExprInfo<'_>) {
3003 macro_rules! lint_with_both_lhs_and_rhs {
3004 ($func:ident, $cx:expr, $info:ident) => {
3005 if !$func($cx, $info) {
3006 ::std::mem::swap(&mut $info.chain, &mut $info.other);
3007 if $func($cx, $info) {
3014 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
3015 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
3016 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
3017 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
3020 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
3022 cx: &LateContext<'_>,
3023 info: &BinaryExprInfo<'_>,
3024 chain_methods: &[&str],
3025 lint: &'static Lint,
3029 if let Some(args) = method_chain_args(info.chain, chain_methods);
3030 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
3031 if arg_char.len() == 1;
3032 if let hir::ExprKind::Path(ref qpath) = fun.kind;
3033 if let Some(segment) = single_segment_path(qpath);
3034 if segment.ident.name == sym!(Some);
3036 let mut applicability = Applicability::MachineApplicable;
3037 let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty_adjusted(&args[0][0]));
3039 if self_ty.kind != ty::Str {
3047 &format!("you should use the `{}` method", suggest),
3049 format!("{}{}.{}({})",
3050 if info.eq { "" } else { "!" },
3051 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
3053 snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
3064 /// Checks for the `CHARS_NEXT_CMP` lint.
3065 fn lint_chars_next_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3066 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
3069 /// Checks for the `CHARS_LAST_CMP` lint.
3070 fn lint_chars_last_cmp<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3071 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
3074 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
3078 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
3079 fn lint_chars_cmp_with_unwrap<'tcx>(
3080 cx: &LateContext<'tcx>,
3081 info: &BinaryExprInfo<'_>,
3082 chain_methods: &[&str],
3083 lint: &'static Lint,
3087 if let Some(args) = method_chain_args(info.chain, chain_methods);
3088 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
3089 if let ast::LitKind::Char(c) = lit.node;
3091 let mut applicability = Applicability::MachineApplicable;
3096 &format!("you should use the `{}` method", suggest),
3098 format!("{}{}.{}('{}')",
3099 if info.eq { "" } else { "!" },
3100 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
3113 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
3114 fn lint_chars_next_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3115 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3118 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3119 fn lint_chars_last_cmp_with_unwrap<'tcx>(cx: &LateContext<'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3120 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3123 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3127 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3128 fn lint_single_char_pattern<'tcx>(cx: &LateContext<'tcx>, _expr: &'tcx hir::Expr<'_>, arg: &'tcx hir::Expr<'_>) {
3130 if let hir::ExprKind::Lit(lit) = &arg.kind;
3131 if let ast::LitKind::Str(r, style) = lit.node;
3132 if r.as_str().len() == 1;
3134 let mut applicability = Applicability::MachineApplicable;
3135 let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
3136 let ch = if let ast::StrStyle::Raw(nhash) = style {
3137 let nhash = nhash as usize;
3138 // for raw string: r##"a"##
3139 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3141 // for regular string: "a"
3142 &snip[1..(snip.len() - 1)]
3144 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3147 SINGLE_CHAR_PATTERN,
3149 "single-character string constant used as pattern",
3150 "try using a `char` instead",
3158 /// Checks for the `USELESS_ASREF` lint.
3159 fn lint_asref(cx: &LateContext<'_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3160 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3161 // check if the call is to the actual `AsRef` or `AsMut` trait
3162 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3163 // check if the type after `as_ref` or `as_mut` is the same as before
3164 let recvr = &as_ref_args[0];
3165 let rcv_ty = cx.typeck_results().expr_ty(recvr);
3166 let res_ty = cx.typeck_results().expr_ty(expr);
3167 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3168 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3169 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3170 // allow the `as_ref` or `as_mut` if it is followed by another method call
3172 if let Some(parent) = get_parent_expr(cx, expr);
3173 if let hir::ExprKind::MethodCall(_, ref span, _, _) = parent.kind;
3174 if span != &expr.span;
3180 let mut applicability = Applicability::MachineApplicable;
3185 &format!("this call to `{}` does nothing", call_name),
3187 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
3194 fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3195 has_iter_method(cx, self_ref_ty).map(|ty_name| {
3196 let mutbl = match self_ref_ty.kind {
3197 ty::Ref(_, _, mutbl) => mutbl,
3198 _ => unreachable!(),
3200 let method_name = match mutbl {
3201 hir::Mutability::Not => "iter",
3202 hir::Mutability::Mut => "iter_mut",
3204 (ty_name, method_name)
3208 fn lint_into_iter(cx: &LateContext<'_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3209 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3212 if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3218 "this `.into_iter()` call is equivalent to `.{}()` and will not move the `{}`",
3222 method_name.to_string(),
3223 Applicability::MachineApplicable,
3228 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3229 fn lint_maybe_uninit(cx: &LateContext<'_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3231 if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3233 if let hir::ExprKind::Path(ref path) = callee.kind;
3234 if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3235 if !is_maybe_uninit_ty_valid(cx, cx.typeck_results().expr_ty_adjusted(outer));
3239 UNINIT_ASSUMED_INIT,
3241 "this call for this type may be undefined behavior"
3247 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_>, ty: Ty<'_>) -> bool {
3249 ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3250 ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3251 ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
3256 fn lint_suspicious_map(cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
3261 "this call to `map()` won't have an effect on the call to `count()`",
3263 "make sure you did not confuse `map` with `filter` or `for_each`",
3267 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3268 fn lint_option_as_ref_deref<'tcx>(
3269 cx: &LateContext<'tcx>,
3270 expr: &hir::Expr<'_>,
3271 as_ref_args: &[hir::Expr<'_>],
3272 map_args: &[hir::Expr<'_>],
3275 let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
3277 let option_ty = cx.typeck_results().expr_ty(&as_ref_args[0]);
3278 if !is_type_diagnostic_item(cx, option_ty, sym!(option_type)) {
3282 let deref_aliases: [&[&str]; 9] = [
3283 &paths::DEREF_TRAIT_METHOD,
3284 &paths::DEREF_MUT_TRAIT_METHOD,
3285 &paths::CSTRING_AS_C_STR,
3286 &paths::OS_STRING_AS_OS_STR,
3287 &paths::PATH_BUF_AS_PATH,
3288 &paths::STRING_AS_STR,
3289 &paths::STRING_AS_MUT_STR,
3290 &paths::VEC_AS_SLICE,
3291 &paths::VEC_AS_MUT_SLICE,
3294 let is_deref = match map_args[1].kind {
3295 hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3296 hir::ExprKind::Closure(_, _, body_id, _, _) => {
3297 let closure_body = cx.tcx.hir().body(body_id);
3298 let closure_expr = remove_blocks(&closure_body.value);
3300 match &closure_expr.kind {
3301 hir::ExprKind::MethodCall(_, _, args, _) => {
3304 if let hir::ExprKind::Path(qpath) = &args[0].kind;
3305 if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, args[0].hir_id);
3306 if closure_body.params[0].pat.hir_id == local_id;
3309 .expr_adjustments(&args[0])
3312 .collect::<Box<[_]>>();
3313 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3315 let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap();
3316 deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3322 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
3324 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind;
3325 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind;
3326 if let hir::ExprKind::Path(ref qpath) = inner2.kind;
3327 if let hir::def::Res::Local(local_id) = cx.qpath_res(qpath, inner2.hir_id);
3329 closure_body.params[0].pat.hir_id == local_id
3342 let current_method = if is_mut {
3343 format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
3345 format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
3347 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3348 let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3349 let suggestion = format!("try using {} instead", method_hint);
3352 "called `{0}` on an Option value. This can be done more directly \
3353 by calling `{1}` instead",
3354 current_method, hint
3358 OPTION_AS_REF_DEREF,
3363 Applicability::MachineApplicable,
3368 /// Given a `Result<T, E>` type, return its error type (`E`).
3369 fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3371 ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym!(result_type)) => substs.types().nth(1),
3376 /// This checks whether a given type is known to implement Debug.
3377 fn has_debug_impl<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
3379 .get_diagnostic_item(sym::debug_trait)
3380 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3385 StartsWith(&'static str),
3389 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3390 (Convention::Eq("new"), &[SelfKind::No]),
3391 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3392 (Convention::StartsWith("from_"), &[SelfKind::No]),
3393 (Convention::StartsWith("into_"), &[SelfKind::Value]),
3394 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3395 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3396 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3399 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3400 unsafety: hir::Unsafety::Normal,
3401 constness: hir::Constness::NotConst,
3402 asyncness: hir::IsAsync::NotAsync,
3403 abi: rustc_target::spec::abi::Abi::Rust,
3407 const TRAIT_METHODS: [(&str, usize, &hir::FnHeader, SelfKind, OutType, &str); 30] = [
3408 ("add", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Add"),
3409 ("as_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
3410 ("as_ref", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
3411 ("bitand", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
3412 ("bitor", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
3413 ("bitxor", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
3414 ("borrow", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
3415 ("borrow_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
3416 ("clone", 1, &FN_HEADER, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
3417 ("cmp", 2, &FN_HEADER, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
3418 ("default", 0, &FN_HEADER, SelfKind::No, OutType::Any, "std::default::Default"),
3419 ("deref", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
3420 ("deref_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
3421 ("div", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Div"),
3422 ("drop", 1, &FN_HEADER, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
3423 ("eq", 2, &FN_HEADER, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
3424 ("from_iter", 1, &FN_HEADER, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
3425 ("from_str", 1, &FN_HEADER, SelfKind::No, OutType::Any, "std::str::FromStr"),
3426 ("hash", 2, &FN_HEADER, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
3427 ("index", 2, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
3428 ("index_mut", 2, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
3429 ("into_iter", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
3430 ("mul", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Mul"),
3431 ("neg", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Neg"),
3432 ("next", 1, &FN_HEADER, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
3433 ("not", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Not"),
3434 ("rem", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Rem"),
3435 ("shl", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Shl"),
3436 ("shr", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Shr"),
3437 ("sub", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Sub"),
3441 const PATTERN_METHODS: [(&str, usize); 17] = [
3449 ("split_terminator", 1),
3450 ("rsplit_terminator", 1),
3455 ("match_indices", 1),
3456 ("rmatch_indices", 1),
3457 ("trim_start_matches", 1),
3458 ("trim_end_matches", 1),
3461 #[derive(Clone, Copy, PartialEq, Debug)]
3470 fn matches<'a>(self, cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3471 fn matches_value<'a>(cx: &LateContext<'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3472 if ty == parent_ty {
3474 } else if ty.is_box() {
3475 ty.boxed_ty() == parent_ty
3476 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3477 if let ty::Adt(_, substs) = ty.kind {
3478 substs.types().next().map_or(false, |t| t == parent_ty)
3487 fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3488 if let ty::Ref(_, t, m) = ty.kind {
3489 return m == mutability && t == parent_ty;
3492 let trait_path = match mutability {
3493 hir::Mutability::Not => &paths::ASREF_TRAIT,
3494 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3497 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3499 None => return false,
3501 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3505 Self::Value => matches_value(cx, parent_ty, ty),
3506 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3507 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3508 Self::No => ty != parent_ty,
3513 fn description(self) -> &'static str {
3515 Self::Value => "self by value",
3516 Self::Ref => "self by reference",
3517 Self::RefMut => "self by mutable reference",
3518 Self::No => "no self",
3525 fn check(&self, other: &str) -> bool {
3527 Self::Eq(this) => this == other,
3528 Self::StartsWith(this) => other.starts_with(this) && this != other,
3533 impl fmt::Display for Convention {
3534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3536 Self::Eq(this) => this.fmt(f),
3537 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3542 #[derive(Clone, Copy)]
3551 fn matches(self, cx: &LateContext<'_>, ty: &hir::FnRetTy<'_>) -> bool {
3552 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3554 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3555 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3556 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3557 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3558 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3564 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3565 if let hir::TyKind::Path(ref p) = ty.kind {
3566 match_qpath(p, &["bool"])
3572 // Returns `true` if `expr` contains a return expression
3573 fn contains_return(expr: &hir::Expr<'_>) -> bool {
3574 struct RetCallFinder {
3578 impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
3579 type Map = Map<'tcx>;
3581 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
3585 if let hir::ExprKind::Ret(..) = &expr.kind {
3588 intravisit::walk_expr(self, expr);
3592 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
3593 intravisit::NestedVisitorMap::None
3597 let mut visitor = RetCallFinder { found: false };
3598 visitor.visit_expr(expr);
3602 fn check_pointer_offset(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3605 if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.typeck_results().expr_ty(&args[0]).kind;
3606 if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3609 span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3614 fn lint_filetype_is_file(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3615 let ty = cx.typeck_results().expr_ty(&args[0]);
3617 if !match_type(cx, ty, &paths::FILE_TYPE) {
3623 let lint_unary: &str;
3624 let help_unary: &str;
3626 if let Some(parent) = get_parent_expr(cx, expr);
3627 if let hir::ExprKind::Unary(op, _) = parent.kind;
3628 if op == hir::UnOp::UnNot;
3641 let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3642 let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3643 span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
3646 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3647 expected.constness == actual.constness
3648 && expected.unsafety == actual.unsafety
3649 && expected.asyncness == actual.asyncness