1 mod inefficient_to_string;
2 mod manual_saturating_arithmetic;
3 mod option_map_unwrap_or;
4 mod unnecessary_filter_map;
10 use if_chain::if_chain;
12 use rustc_errors::Applicability;
14 use rustc_hir::intravisit::{self, Visitor};
15 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::lint::in_external_macro;
18 use rustc_middle::ty::subst::GenericArgKind;
19 use rustc_middle::ty::{self, Predicate, Ty};
20 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 use rustc_span::source_map::Span;
22 use rustc_span::symbol::{sym, Symbol, SymbolStr};
24 use crate::consts::{constant, Constant};
25 use crate::utils::usage::mutated_variables;
27 get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, implements_trait, in_macro, is_copy,
28 is_ctor_or_promotable_const_function, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
29 match_def_path, match_qpath, match_trait_method, match_type, match_var, method_calls, method_chain_args, paths,
30 remove_blocks, return_ty, same_tys, single_segment_path, snippet, snippet_with_applicability,
31 snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
32 span_lint_and_then, sugg, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
35 declare_clippy_lint! {
36 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
38 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
39 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
40 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
41 /// `Allow` by default.
43 /// **Known problems:** None.
47 /// Using unwrap on an `Option`:
50 /// let opt = Some(1);
57 /// let opt = Some(1);
58 /// opt.expect("more helpful message");
60 pub OPTION_UNWRAP_USED,
62 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
65 declare_clippy_lint! {
66 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
68 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
69 /// values. Normally, you want to implement more sophisticated error handling,
70 /// and propagate errors upwards with `?` operator.
72 /// Even if you want to panic on errors, not all `Error`s implement good
73 /// messages on display. Therefore, it may be beneficial to look at the places
74 /// where they may get displayed. Activate this lint to do just that.
76 /// **Known problems:** None.
79 /// Using unwrap on an `Result`:
82 /// let res: Result<usize, ()> = Ok(1);
89 /// let res: Result<usize, ()> = Ok(1);
90 /// res.expect("more helpful message");
92 pub RESULT_UNWRAP_USED,
94 "using `Result.unwrap()`, which might be better handled"
97 declare_clippy_lint! {
98 /// **What it does:** Checks for `.expect()` calls on `Option`s.
100 /// **Why is this bad?** Usually it is better to handle the `None` case. Still,
101 /// for a lot of quick-and-dirty code, `expect` is a good choice, which is why
102 /// this lint is `Allow` by default.
104 /// **Known problems:** None.
108 /// Using expect on an `Option`:
111 /// let opt = Some(1);
112 /// opt.expect("one");
118 /// let opt = Some(1);
121 pub OPTION_EXPECT_USED,
123 "using `Option.expect()`, which might be better handled"
126 declare_clippy_lint! {
127 /// **What it does:** Checks for `.expect()` calls on `Result`s.
129 /// **Why is this bad?** `result.expect()` will let the thread panic on `Err`
130 /// values. Normally, you want to implement more sophisticated error handling,
131 /// and propagate errors upwards with `?` operator.
133 /// **Known problems:** None.
136 /// Using expect on an `Result`:
139 /// let res: Result<usize, ()> = Ok(1);
140 /// res.expect("one");
146 /// let res: Result<usize, ()> = Ok(1);
148 /// # Ok::<(), ()>(())
150 pub RESULT_EXPECT_USED,
152 "using `Result.expect()`, which might be better handled"
155 declare_clippy_lint! {
156 /// **What it does:** Checks for methods that should live in a trait
157 /// implementation of a `std` trait (see [llogiq's blog
158 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
159 /// information) instead of an inherent implementation.
161 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
162 /// the code, often with very little cost. Also people seeing a `mul(...)`
164 /// may expect `*` to work equally, so you should have good reason to disappoint
167 /// **Known problems:** None.
173 /// fn add(&self, other: &X) -> X {
179 pub SHOULD_IMPLEMENT_TRAIT,
181 "defining a method that should be implementing a std trait"
184 declare_clippy_lint! {
185 /// **What it does:** Checks for methods with certain name prefixes and which
186 /// doesn't match how self is taken. The actual rules are:
188 /// |Prefix |`self` taken |
189 /// |-------|----------------------|
190 /// |`as_` |`&self` or `&mut self`|
192 /// |`into_`|`self` |
193 /// |`is_` |`&self` or none |
194 /// |`to_` |`&self` |
196 /// **Why is this bad?** Consistency breeds readability. If you follow the
197 /// conventions, your users won't be surprised that they, e.g., need to supply a
198 /// mutable reference to a `as_..` function.
200 /// **Known problems:** None.
206 /// fn as_str(self) -> &'static str {
212 pub WRONG_SELF_CONVENTION,
214 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
217 declare_clippy_lint! {
218 /// **What it does:** This is the same as
219 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
221 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
223 /// **Known problems:** Actually *renaming* the function may break clients if
224 /// the function is part of the public interface. In that case, be mindful of
225 /// the stability guarantees you've given your users.
231 /// pub fn as_str(self) -> &'a str {
236 pub WRONG_PUB_SELF_CONVENTION,
238 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
241 declare_clippy_lint! {
242 /// **What it does:** Checks for usage of `ok().expect(..)`.
244 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
245 /// directly to get a better error message.
247 /// **Known problems:** The error type needs to implement `Debug`
251 /// # let x = Ok::<_, ()>(());
252 /// x.ok().expect("why did I do this again?")
256 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
259 declare_clippy_lint! {
260 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
262 /// **Why is this bad?** Readability, this can be written more concisely as
263 /// `_.map_or(_, _)`.
265 /// **Known problems:** The order of the arguments is not in execution order
269 /// # let x = Some(1);
270 /// x.map(|a| a + 1).unwrap_or(0);
272 pub OPTION_MAP_UNWRAP_OR,
274 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as `map_or(a, f)`"
277 declare_clippy_lint! {
278 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
280 /// **Why is this bad?** Readability, this can be written more concisely as
281 /// `_.map_or_else(_, _)`.
283 /// **Known problems:** The order of the arguments is not in execution order.
287 /// # let x = Some(1);
288 /// # fn some_function() -> usize { 1 }
289 /// x.map(|a| a + 1).unwrap_or_else(some_function);
291 pub OPTION_MAP_UNWRAP_OR_ELSE,
293 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `map_or_else(g, f)`"
296 declare_clippy_lint! {
297 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
299 /// **Why is this bad?** Readability, this can be written more concisely as
300 /// `result.map_or_else(_, _)`.
302 /// **Known problems:** None.
306 /// # let x: Result<usize, ()> = Ok(1);
307 /// # fn some_function(foo: ()) -> usize { 1 }
308 /// x.map(|a| a + 1).unwrap_or_else(some_function);
310 pub RESULT_MAP_UNWRAP_OR_ELSE,
312 "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `.map_or_else(g, f)`"
315 declare_clippy_lint! {
316 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
318 /// **Why is this bad?** Readability, this can be written more concisely as
321 /// **Known problems:** The order of the arguments is not in execution order.
325 /// # let opt = Some(1);
326 /// opt.map_or(None, |a| Some(a + 1))
329 pub OPTION_MAP_OR_NONE,
331 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
334 declare_clippy_lint! {
335 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`.
337 /// **Why is this bad?** Readability, this can be written more concisely as
340 /// **Known problems:** None
345 /// let x = Some("foo");
346 /// let _ = x.and_then(|s| Some(s.len()));
349 /// The correct use would be:
352 /// let x = Some("foo");
353 /// let _ = x.map(|s| s.len());
355 pub OPTION_AND_THEN_SOME,
357 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
360 declare_clippy_lint! {
361 /// **What it does:** Checks for usage of `_.filter(_).next()`.
363 /// **Why is this bad?** Readability, this can be written more concisely as
366 /// **Known problems:** None.
370 /// # let vec = vec![1];
371 /// vec.iter().filter(|x| **x == 0).next();
373 /// Could be written as
375 /// # let vec = vec![1];
376 /// vec.iter().find(|x| **x == 0);
380 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
383 declare_clippy_lint! {
384 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
386 /// **Why is this bad?** Readability, this can be written more concisely as
387 /// `_.find(!condition)`.
389 /// **Known problems:** None.
393 /// # let vec = vec![1];
394 /// vec.iter().skip_while(|x| **x == 0).next();
396 /// Could be written as
398 /// # let vec = vec![1];
399 /// vec.iter().find(|x| **x != 0);
403 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
406 declare_clippy_lint! {
407 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
409 /// **Why is this bad?** Readability, this can be written more concisely as a
410 /// single method call.
412 /// **Known problems:**
416 /// let vec = vec![vec![1]];
417 /// vec.iter().map(|x| x.iter()).flatten();
421 "using combinations of `flatten` and `map` which can usually be written as a single method call"
424 declare_clippy_lint! {
425 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
426 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
428 /// **Why is this bad?** Readability, this can be written more concisely as a
429 /// single method call.
431 /// **Known problems:** Often requires a condition + Option/Iterator creation
432 /// inside the closure.
436 /// let vec = vec![1];
437 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
441 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
444 declare_clippy_lint! {
445 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
447 /// **Why is this bad?** Readability, this can be written more concisely as a
448 /// single method call.
450 /// **Known problems:** None
454 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
456 /// Can be written as
459 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
463 "using combination of `filter_map` and `next` which can usually be written as a single method call"
466 declare_clippy_lint! {
467 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
469 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
471 /// **Known problems:** None
475 /// # let iter = vec![vec![0]].into_iter();
476 /// iter.flat_map(|x| x);
478 /// Can be written as
480 /// # let iter = vec![vec![0]].into_iter();
483 pub FLAT_MAP_IDENTITY,
485 "call to `flat_map` where `flatten` is sufficient"
488 declare_clippy_lint! {
489 /// **What it does:** Checks for usage of `_.find(_).map(_)`.
491 /// **Why is this bad?** Readability, this can be written more concisely as a
492 /// single method call.
494 /// **Known problems:** Often requires a condition + Option/Iterator creation
495 /// inside the closure.
499 /// (0..3).find(|x| *x == 2).map(|x| x * 2);
501 /// Can be written as
503 /// (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
507 "using a combination of `find` and `map` can usually be written as a single method call"
510 declare_clippy_lint! {
511 /// **What it does:** Checks for an iterator search (such as `find()`,
512 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
514 /// **Why is this bad?** Readability, this can be written more concisely as
517 /// **Known problems:** None.
521 /// # let vec = vec![1];
522 /// vec.iter().find(|x| **x == 0).is_some();
524 /// Could be written as
526 /// # let vec = vec![1];
527 /// vec.iter().any(|x| *x == 0);
531 "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
534 declare_clippy_lint! {
535 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
536 /// if it starts with a given char.
538 /// **Why is this bad?** Readability, this can be written more concisely as
539 /// `_.starts_with(_)`.
541 /// **Known problems:** None.
545 /// let name = "foo";
546 /// if name.chars().next() == Some('_') {};
548 /// Could be written as
550 /// let name = "foo";
551 /// if name.starts_with('_') {};
555 "using `.chars().next()` to check if a string starts with a char"
558 declare_clippy_lint! {
559 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
560 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
561 /// `unwrap_or_default` instead.
563 /// **Why is this bad?** The function will always be called and potentially
564 /// allocate an object acting as the default.
566 /// **Known problems:** If the function has side-effects, not calling it will
567 /// change the semantic of the program, but you shouldn't rely on that anyway.
571 /// # let foo = Some(String::new());
572 /// foo.unwrap_or(String::new());
574 /// this can instead be written:
576 /// # let foo = Some(String::new());
577 /// foo.unwrap_or_else(String::new);
581 /// # let foo = Some(String::new());
582 /// foo.unwrap_or_default();
586 "using any `*or` method with a function call, which suggests `*or_else`"
589 declare_clippy_lint! {
590 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
591 /// etc., and suggests to use `unwrap_or_else` instead
593 /// **Why is this bad?** The function will always be called.
595 /// **Known problems:** If the function has side-effects, not calling it will
596 /// change the semantics of the program, but you shouldn't rely on that anyway.
600 /// # let foo = Some(String::new());
601 /// # let err_code = "418";
602 /// # let err_msg = "I'm a teapot";
603 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
607 /// # let foo = Some(String::new());
608 /// # let err_code = "418";
609 /// # let err_msg = "I'm a teapot";
610 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
612 /// this can instead be written:
614 /// # let foo = Some(String::new());
615 /// # let err_code = "418";
616 /// # let err_msg = "I'm a teapot";
617 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
621 "using any `expect` method with a function call"
624 declare_clippy_lint! {
625 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
627 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
628 /// generics, not for using the `clone` method on a concrete type.
630 /// **Known problems:** None.
638 "using `clone` on a `Copy` type"
641 declare_clippy_lint! {
642 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
643 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
644 /// function syntax instead (e.g., `Rc::clone(foo)`).
646 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
647 /// can obscure the fact that only the pointer is being cloned, not the underlying
652 /// # use std::rc::Rc;
653 /// let x = Rc::new(1);
656 pub CLONE_ON_REF_PTR,
658 "using 'clone' on a ref-counted pointer"
661 declare_clippy_lint! {
662 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
664 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
665 /// cloning the underlying `T`.
667 /// **Known problems:** None.
674 /// let z = y.clone();
675 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
678 pub CLONE_DOUBLE_REF,
680 "using `clone` on `&&T`"
683 declare_clippy_lint! {
684 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
685 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
687 /// **Why is this bad?** This bypasses the specialized implementation of
688 /// `ToString` and instead goes through the more expensive string formatting
691 /// **Known problems:** None.
695 /// // Generic implementation for `T: Display` is used (slow)
696 /// ["foo", "bar"].iter().map(|s| s.to_string());
698 /// // OK, the specialized impl is used
699 /// ["foo", "bar"].iter().map(|&s| s.to_string());
701 pub INEFFICIENT_TO_STRING,
703 "using `to_string` on `&&T` where `T: ToString`"
706 declare_clippy_lint! {
707 /// **What it does:** Checks for `new` not returning `Self`.
709 /// **Why is this bad?** As a convention, `new` methods are used to make a new
710 /// instance of a type.
712 /// **Known problems:** None.
717 /// # struct NotAFoo;
719 /// fn new() -> NotAFoo {
726 "not returning `Self` in a `new` method"
729 declare_clippy_lint! {
730 /// **What it does:** Checks for string methods that receive a single-character
731 /// `str` as an argument, e.g., `_.split("x")`.
733 /// **Why is this bad?** Performing these methods using a `char` is faster than
736 /// **Known problems:** Does not catch multi-byte unicode characters.
739 /// `_.split("x")` could be `_.split('x')`
740 pub SINGLE_CHAR_PATTERN,
742 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
745 declare_clippy_lint! {
746 /// **What it does:** Checks for getting the inner pointer of a temporary
749 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
750 /// as the `CString` is alive.
752 /// **Known problems:** None.
756 /// # use std::ffi::CString;
757 /// # fn call_some_ffi_func(_: *const i8) {}
759 /// let c_str = CString::new("foo").unwrap().as_ptr();
761 /// call_some_ffi_func(c_str);
764 /// Here `c_str` point to a freed address. The correct use would be:
766 /// # use std::ffi::CString;
767 /// # fn call_some_ffi_func(_: *const i8) {}
769 /// let c_str = CString::new("foo").unwrap();
771 /// call_some_ffi_func(c_str.as_ptr());
774 pub TEMPORARY_CSTRING_AS_PTR,
776 "getting the inner pointer of a temporary `CString`"
779 declare_clippy_lint! {
780 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
782 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
783 /// actually intend to panic.
785 /// **Known problems:** None.
788 /// ```rust,should_panic
789 /// for x in (0..100).step_by(0) {
793 pub ITERATOR_STEP_BY_ZERO,
795 "using `Iterator::step_by(0)`, which will panic at runtime"
798 declare_clippy_lint! {
799 /// **What it does:** Checks for the use of `iter.nth(0)`.
801 /// **Why is this bad?** `iter.next()` is equivalent to
802 /// `iter.nth(0)`, as they both consume the next element,
803 /// but is more readable.
805 /// **Known problems:** None.
810 /// # use std::collections::HashSet;
812 /// # let mut s = HashSet::new();
814 /// let x = s.iter().nth(0);
817 /// # let mut s = HashSet::new();
819 /// let x = s.iter().next();
823 "replace `iter.nth(0)` with `iter.next()`"
826 declare_clippy_lint! {
827 /// **What it does:** Checks for use of `.iter().nth()` (and the related
828 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
830 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
833 /// **Known problems:** None.
837 /// let some_vec = vec![0, 1, 2, 3];
838 /// let bad_vec = some_vec.iter().nth(3);
839 /// let bad_slice = &some_vec[..].iter().nth(3);
841 /// The correct use would be:
843 /// let some_vec = vec![0, 1, 2, 3];
844 /// let bad_vec = some_vec.get(3);
845 /// let bad_slice = &some_vec[..].get(3);
849 "using `.iter().nth()` on a standard library type with O(1) element access"
852 declare_clippy_lint! {
853 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
855 /// **Why is this bad?** `.nth(x)` is cleaner
857 /// **Known problems:** None.
861 /// let some_vec = vec![0, 1, 2, 3];
862 /// let bad_vec = some_vec.iter().skip(3).next();
863 /// let bad_slice = &some_vec[..].iter().skip(3).next();
865 /// The correct use would be:
867 /// let some_vec = vec![0, 1, 2, 3];
868 /// let bad_vec = some_vec.iter().nth(3);
869 /// let bad_slice = &some_vec[..].iter().nth(3);
873 "using `.skip(x).next()` on an iterator"
876 declare_clippy_lint! {
877 /// **What it does:** Checks for use of `.get().unwrap()` (or
878 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
880 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
883 /// **Known problems:** Not a replacement for error handling: Using either
884 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
885 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
886 /// temporary placeholder for dealing with the `Option` type, then this does
887 /// not mitigate the need for error handling. If there is a chance that `.get()`
888 /// will be `None` in your program, then it is advisable that the `None` case
889 /// is handled in a future refactor instead of using `.unwrap()` or the Index
894 /// let mut some_vec = vec![0, 1, 2, 3];
895 /// let last = some_vec.get(3).unwrap();
896 /// *some_vec.get_mut(0).unwrap() = 1;
898 /// The correct use would be:
900 /// let mut some_vec = vec![0, 1, 2, 3];
901 /// let last = some_vec[3];
906 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
909 declare_clippy_lint! {
910 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
911 /// `&str` or `String`.
913 /// **Why is this bad?** `.push_str(s)` is clearer
915 /// **Known problems:** None.
920 /// let def = String::from("def");
921 /// let mut s = String::new();
922 /// s.extend(abc.chars());
923 /// s.extend(def.chars());
925 /// The correct use would be:
928 /// let def = String::from("def");
929 /// let mut s = String::new();
931 /// s.push_str(&def);
933 pub STRING_EXTEND_CHARS,
935 "using `x.extend(s.chars())` where s is a `&str` or `String`"
938 declare_clippy_lint! {
939 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
942 /// **Why is this bad?** `.to_vec()` is clearer
944 /// **Known problems:** None.
948 /// let s = [1, 2, 3, 4, 5];
949 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
951 /// The better use would be:
953 /// let s = [1, 2, 3, 4, 5];
954 /// let s2: Vec<isize> = s.to_vec();
956 pub ITER_CLONED_COLLECT,
958 "using `.cloned().collect()` on slice to create a `Vec`"
961 declare_clippy_lint! {
962 /// **What it does:** Checks for usage of `.chars().last()` or
963 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
965 /// **Why is this bad?** Readability, this can be written more concisely as
966 /// `_.ends_with(_)`.
968 /// **Known problems:** None.
972 /// # let name = "_";
973 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
978 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
981 declare_clippy_lint! {
982 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
983 /// types before and after the call are the same.
985 /// **Why is this bad?** The call is unnecessary.
987 /// **Known problems:** None.
991 /// # fn do_stuff(x: &[i32]) {}
992 /// let x: &[i32] = &[1, 2, 3, 4, 5];
993 /// do_stuff(x.as_ref());
995 /// The correct use would be:
997 /// # fn do_stuff(x: &[i32]) {}
998 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1003 "using `as_ref` where the types before and after the call are the same"
1006 declare_clippy_lint! {
1007 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1008 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1009 /// `sum` or `product`.
1011 /// **Why is this bad?** Readability.
1013 /// **Known problems:** False positive in pattern guards. Will be resolved once
1014 /// non-lexical lifetimes are stable.
1018 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1020 /// This could be written as:
1022 /// let _ = (0..3).any(|x| x > 2);
1024 pub UNNECESSARY_FOLD,
1026 "using `fold` when a more succinct alternative exists"
1029 declare_clippy_lint! {
1030 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1031 /// More specifically it checks if the closure provided is only performing one of the
1032 /// filter or map operations and suggests the appropriate option.
1034 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1035 /// operation is being performed.
1037 /// **Known problems:** None
1041 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1043 /// As there is no transformation of the argument this could be written as:
1045 /// let _ = (0..3).filter(|&x| x > 2);
1049 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1051 /// As there is no conditional check on the argument this could be written as:
1053 /// let _ = (0..4).map(|x| x + 1);
1055 pub UNNECESSARY_FILTER_MAP,
1057 "using `filter_map` when a more succinct alternative exists"
1060 declare_clippy_lint! {
1061 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1064 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1065 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1066 /// `iter_mut` directly.
1068 /// **Known problems:** None
1073 /// let _ = (&vec![3, 4, 5]).into_iter();
1075 pub INTO_ITER_ON_REF,
1077 "using `.into_iter()` on a reference"
1080 declare_clippy_lint! {
1081 /// **What it does:** Checks for calls to `map` followed by a `count`.
1083 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1084 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1085 /// drive the iterator to completion, you can just use `for_each` instead.
1087 /// **Known problems:** None
1092 /// let _ = (0..3).map(|x| x + 2).count();
1096 "suspicious usage of map"
1099 declare_clippy_lint! {
1100 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1102 /// **Why is this bad?** For most types, this is undefined behavior.
1104 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1105 /// of `MaybeUninit`. There may be other types that allow uninitialized
1106 /// data, but those are not yet rigorously defined.
1111 /// // Beware the UB
1112 /// use std::mem::MaybeUninit;
1114 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1117 /// Note that the following is OK:
1120 /// use std::mem::MaybeUninit;
1122 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1123 /// MaybeUninit::uninit().assume_init()
1126 pub UNINIT_ASSUMED_INIT,
1128 "`MaybeUninit::uninit().assume_init()`"
1131 declare_clippy_lint! {
1132 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1134 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1139 /// # let y: u32 = 0;
1140 /// # let x: u32 = 100;
1141 /// let add = x.checked_add(y).unwrap_or(u32::max_value());
1142 /// let sub = x.checked_sub(y).unwrap_or(u32::min_value());
1145 /// can be written using dedicated methods for saturating addition/subtraction as:
1148 /// # let y: u32 = 0;
1149 /// # let x: u32 = 100;
1150 /// let add = x.saturating_add(y);
1151 /// let sub = x.saturating_sub(y);
1153 pub MANUAL_SATURATING_ARITHMETIC,
1155 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1158 declare_clippy_lint! {
1159 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1160 /// zero-sized types
1162 /// **Why is this bad?** This is a no-op, and likely unintended
1164 /// **Known problems:** None
1168 /// unsafe { (&() as *const ()).offset(1) };
1172 "Check for offset calculations on raw pointers to zero-sized types"
1175 declare_clippy_lint! {
1176 /// **What it does:** Checks for `FileType::is_file()`.
1178 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1179 /// they are testing whether a path is something they can get bytes from. But
1180 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1181 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1187 /// let metadata = std::fs::metadata("foo.txt")?;
1188 /// let filetype = metadata.file_type();
1190 /// if filetype.is_file() {
1193 /// # Ok::<_, std::io::Error>(())
1197 /// should be written as:
1201 /// let metadata = std::fs::metadata("foo.txt")?;
1202 /// let filetype = metadata.file_type();
1204 /// if !filetype.is_dir() {
1207 /// # Ok::<_, std::io::Error>(())
1210 pub FILETYPE_IS_FILE,
1212 "`FileType::is_file` is not recommended to test for readable file type"
1215 declare_clippy_lint! {
1216 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1218 /// **Why is this bad?** Readability, this can be written more concisely as a
1219 /// single method call.
1221 /// **Known problems:** None.
1225 /// # let opt = Some("".to_string());
1226 /// opt.as_ref().map(String::as_str)
1229 /// Can be written as
1231 /// # let opt = Some("".to_string());
1235 pub OPTION_AS_REF_DEREF,
1237 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1240 declare_lint_pass!(Methods => [
1245 SHOULD_IMPLEMENT_TRAIT,
1246 WRONG_SELF_CONVENTION,
1247 WRONG_PUB_SELF_CONVENTION,
1249 OPTION_MAP_UNWRAP_OR,
1250 OPTION_MAP_UNWRAP_OR_ELSE,
1251 RESULT_MAP_UNWRAP_OR_ELSE,
1253 OPTION_AND_THEN_SOME,
1261 INEFFICIENT_TO_STRING,
1263 SINGLE_CHAR_PATTERN,
1265 TEMPORARY_CSTRING_AS_PTR,
1273 ITERATOR_STEP_BY_ZERO,
1278 STRING_EXTEND_CHARS,
1279 ITER_CLONED_COLLECT,
1282 UNNECESSARY_FILTER_MAP,
1285 UNINIT_ASSUMED_INIT,
1286 MANUAL_SATURATING_ARITHMETIC,
1289 OPTION_AS_REF_DEREF,
1292 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
1293 #[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
1294 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
1295 if in_macro(expr.span) {
1299 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1300 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1301 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1303 match method_names.as_slice() {
1304 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1305 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1306 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1307 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1308 ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1309 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1310 ["unwrap_or_else", "map"] => lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]),
1311 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1312 ["and_then", ..] => lint_option_and_then_some(cx, expr, arg_lists[0]),
1313 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1314 ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1315 ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
1316 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1317 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
1318 ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
1319 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1320 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1321 ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1322 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1323 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1324 ["is_some", "position"] => {
1325 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1327 ["is_some", "rposition"] => {
1328 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1330 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1331 ["as_ptr", "unwrap"] | ["as_ptr", "expect"] => {
1332 lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0])
1334 ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1335 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1336 ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1337 ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1338 ["next", "skip"] => lint_iter_skip_next(cx, expr),
1339 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1340 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1341 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1342 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1343 ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
1344 ["count", "map"] => lint_suspicious_map(cx, expr),
1345 ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1346 ["unwrap_or", arith @ "checked_add"]
1347 | ["unwrap_or", arith @ "checked_sub"]
1348 | ["unwrap_or", arith @ "checked_mul"] => {
1349 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1351 ["add"] | ["offset"] | ["sub"] | ["wrapping_offset"] | ["wrapping_add"] | ["wrapping_sub"] => {
1352 check_pointer_offset(cx, expr, arg_lists[0])
1354 ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1355 ["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
1356 ["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
1361 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
1362 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1363 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1365 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
1366 if args.len() == 1 && method_call.ident.name == sym!(clone) {
1367 lint_clone_on_copy(cx, expr, &args[0], self_ty);
1368 lint_clone_on_ref_ptr(cx, expr, &args[0]);
1370 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1371 inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1374 match self_ty.kind {
1375 ty::Ref(_, ty, _) if ty.kind == ty::Str => {
1376 for &(method, pos) in &PATTERN_METHODS {
1377 if method_call.ident.name.as_str() == method && args.len() > pos {
1378 lint_single_char_pattern(cx, expr, &args[pos]);
1382 ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
1383 lint_into_iter(cx, expr, self_ty, *method_span);
1388 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1389 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1391 let mut info = BinaryExprInfo {
1395 eq: op.node == hir::BinOpKind::Eq,
1397 lint_binary_expr_with_method_call(cx, &mut info);
1403 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1404 if in_external_macro(cx.sess(), impl_item.span) {
1407 let name = impl_item.ident.name.as_str();
1408 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
1409 let item = cx.tcx.hir().expect_item(parent);
1410 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1411 let self_ty = cx.tcx.type_of(def_id);
1413 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1414 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1415 if let hir::ItemKind::Impl{ of_trait: None, .. } = item.kind;
1417 let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
1418 let method_sig = cx.tcx.fn_sig(method_def_id);
1419 let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
1421 let first_arg_ty = &method_sig.inputs().iter().next();
1423 // check conventions w.r.t. conversion method names and predicates
1424 if let Some(first_arg_ty) = first_arg_ty;
1427 if cx.access_levels.is_exported(impl_item.hir_id) {
1428 // check missing trait implementations
1429 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
1430 if name == method_name &&
1431 sig.decl.inputs.len() == n_args &&
1432 out_type.matches(cx, &sig.decl.output) &&
1433 self_kind.matches(cx, self_ty, first_arg_ty) {
1434 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, impl_item.span, &format!(
1435 "defining a method called `{}` on this type; consider implementing \
1436 the `{}` trait or choosing a less ambiguous name", name, trait_name));
1441 if let Some((ref conv, self_kinds)) = &CONVENTIONS
1443 .find(|(ref conv, _)| conv.check(&name))
1445 if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
1446 let lint = if item.vis.node.is_pub() {
1447 WRONG_PUB_SELF_CONVENTION
1449 WRONG_SELF_CONVENTION
1457 "methods called `{}` usually take {}; consider choosing a less \
1462 .map(|k| k.description())
1463 .collect::<Vec<_>>()
1472 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1473 let ret_ty = return_ty(cx, impl_item.hir_id);
1475 let contains_self_ty = |ty: Ty<'tcx>| {
1476 ty.walk().any(|inner| match inner.unpack() {
1477 GenericArgKind::Type(inner_ty) => same_tys(cx, self_ty, inner_ty),
1479 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
1483 // walk the return type and check for Self (this does not check associated types)
1484 if contains_self_ty(ret_ty) {
1488 // if return type is impl trait, check the associated types
1489 if let ty::Opaque(def_id, _) = ret_ty.kind {
1490 // one of the associated types must be Self
1491 for predicate in cx.tcx.predicates_of(def_id).predicates {
1493 (Predicate::Projection(poly_projection_predicate), _) => {
1494 let binder = poly_projection_predicate.ty();
1495 let associated_type = binder.skip_binder();
1497 // walk the associated type and check for Self
1498 if contains_self_ty(associated_type) {
1507 if name == "new" && !same_tys(cx, ret_ty, self_ty) {
1512 "methods called `new` usually return `Self`",
1519 /// Checks for the `OR_FUN_CALL` lint.
1520 #[allow(clippy::too_many_lines)]
1521 fn lint_or_fun_call<'a, 'tcx>(
1522 cx: &LateContext<'a, 'tcx>,
1523 expr: &hir::Expr<'_>,
1526 args: &'tcx [hir::Expr<'_>],
1528 // Searches an expression for method calls or function calls that aren't ctors
1529 struct FunCallFinder<'a, 'tcx> {
1530 cx: &'a LateContext<'a, 'tcx>,
1534 impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
1535 type Map = Map<'tcx>;
1537 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
1538 let call_found = match &expr.kind {
1539 // ignore enum and struct constructors
1540 hir::ExprKind::Call(..) => !is_ctor_or_promotable_const_function(self.cx, expr),
1541 hir::ExprKind::MethodCall(..) => true,
1550 intravisit::walk_expr(self, expr);
1554 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1555 intravisit::NestedVisitorMap::None
1559 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1560 fn check_unwrap_or_default(
1561 cx: &LateContext<'_, '_>,
1563 fun: &hir::Expr<'_>,
1564 self_expr: &hir::Expr<'_>,
1565 arg: &hir::Expr<'_>,
1571 if name == "unwrap_or";
1572 if let hir::ExprKind::Path(ref qpath) = fun.kind;
1573 let path = &*last_path_segment(qpath).ident.as_str();
1574 if ["default", "new"].contains(&path);
1575 let arg_ty = cx.tables.expr_ty(arg);
1576 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1577 if implements_trait(cx, arg_ty, default_trait_id, &[]);
1580 let mut applicability = Applicability::MachineApplicable;
1585 &format!("use of `{}` followed by a call to `{}`", name, path),
1588 "{}.unwrap_or_default()",
1589 snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
1601 /// Checks for `*or(foo())`.
1602 #[allow(clippy::too_many_arguments)]
1603 fn check_general_case<'a, 'tcx>(
1604 cx: &LateContext<'a, 'tcx>,
1608 self_expr: &hir::Expr<'_>,
1609 arg: &'tcx hir::Expr<'_>,
1613 // (path, fn_has_argument, methods, suffix)
1614 let know_types: &[(&[_], _, &[_], _)] = &[
1615 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1616 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1617 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1618 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1622 if know_types.iter().any(|k| k.2.contains(&name));
1624 let mut finder = FunCallFinder { cx: &cx, found: false };
1625 if { finder.visit_expr(&arg); finder.found };
1626 if !contains_return(&arg);
1628 let self_ty = cx.tables.expr_ty(self_expr);
1630 if let Some(&(_, fn_has_arguments, poss, suffix)) =
1631 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
1633 if poss.contains(&name);
1636 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1637 (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1638 (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1639 (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1641 let span_replace_word = method_span.with_hi(span.hi());
1646 &format!("use of `{}` followed by a function call", name),
1648 format!("{}_{}({})", name, suffix, sugg),
1649 Applicability::HasPlaceholders,
1655 if args.len() == 2 {
1656 match args[1].kind {
1657 hir::ExprKind::Call(ref fun, ref or_args) => {
1658 let or_has_args = !or_args.is_empty();
1659 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1672 hir::ExprKind::MethodCall(_, span, ref or_args) => check_general_case(
1679 !or_args.is_empty(),
1687 /// Checks for the `EXPECT_FUN_CALL` lint.
1688 #[allow(clippy::too_many_lines)]
1689 fn lint_expect_fun_call(
1690 cx: &LateContext<'_, '_>,
1691 expr: &hir::Expr<'_>,
1694 args: &[hir::Expr<'_>],
1696 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1698 fn get_arg_root<'a>(cx: &LateContext<'_, '_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1699 let mut arg_root = arg;
1701 arg_root = match &arg_root.kind {
1702 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1703 hir::ExprKind::MethodCall(method_name, _, call_args) => {
1704 if call_args.len() == 1
1705 && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1707 let arg_type = cx.tables.expr_ty(&call_args[0]);
1708 let base_type = walk_ptrs_ty(arg_type);
1709 base_type.kind == ty::Str || match_type(cx, base_type, &paths::STRING)
1723 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1724 // converted to string.
1725 fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1726 let arg_ty = cx.tables.expr_ty(arg);
1727 if match_type(cx, arg_ty, &paths::STRING) {
1730 if let ty::Ref(_, ty, ..) = arg_ty.kind {
1731 if ty.kind == ty::Str && can_be_static_str(cx, arg) {
1738 // Check if an expression could have type `&'static str`, knowing that it
1739 // has type `&str` for some lifetime.
1740 fn can_be_static_str(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1742 hir::ExprKind::Lit(_) => true,
1743 hir::ExprKind::Call(fun, _) => {
1744 if let hir::ExprKind::Path(ref p) = fun.kind {
1745 match cx.tables.qpath_res(p, fun.hir_id) {
1746 hir::def::Res::Def(hir::def::DefKind::Fn, def_id)
1747 | hir::def::Res::Def(hir::def::DefKind::AssocFn, def_id) => matches!(
1748 cx.tcx.fn_sig(def_id).output().skip_binder().kind,
1749 ty::Ref(ty::ReStatic, ..)
1757 hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(arg.hir_id).map_or(false, |method_id| {
1759 cx.tcx.fn_sig(method_id).output().skip_binder().kind,
1760 ty::Ref(ty::ReStatic, ..)
1763 hir::ExprKind::Path(ref p) => match cx.tables.qpath_res(p, arg.hir_id) {
1764 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _) => true,
1771 fn generate_format_arg_snippet(
1772 cx: &LateContext<'_, '_>,
1774 applicability: &mut Applicability,
1777 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1778 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1779 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
1784 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1792 fn is_call(node: &hir::ExprKind<'_>) -> bool {
1794 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
1797 hir::ExprKind::Call(..)
1798 | hir::ExprKind::MethodCall(..)
1799 // These variants are debatable or require further examination
1800 | hir::ExprKind::Match(..)
1801 | hir::ExprKind::Block{ .. } => true,
1806 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
1810 let receiver_type = cx.tables.expr_ty_adjusted(&args[0]);
1811 let closure_args = if match_type(cx, receiver_type, &paths::OPTION) {
1813 } else if match_type(cx, receiver_type, &paths::RESULT) {
1819 let arg_root = get_arg_root(cx, &args[1]);
1821 let span_replace_word = method_span.with_hi(expr.span.hi());
1823 let mut applicability = Applicability::MachineApplicable;
1825 //Special handling for `format!` as arg_root
1827 if let hir::ExprKind::Block(block, None) = &arg_root.kind;
1828 if block.stmts.len() == 1;
1829 if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
1830 if let Some(arg_root) = &local.init;
1831 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
1832 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
1833 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
1835 let fmt_spec = &format_args[0];
1836 let fmt_args = &format_args[1];
1838 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1840 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1842 let sugg = args.join(", ");
1848 &format!("use of `{}` followed by a function call", name),
1850 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1858 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1859 if requires_to_string(cx, arg_root) {
1860 arg_root_snippet.to_mut().push_str(".to_string()");
1867 &format!("use of `{}` followed by a function call", name),
1869 format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1874 /// Checks for the `CLONE_ON_COPY` lint.
1875 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
1876 let ty = cx.tables.expr_ty(expr);
1877 if let ty::Ref(_, inner, _) = arg_ty.kind {
1878 if let ty::Ref(_, innermost, _) = inner.kind {
1883 "using `clone` on a double-reference; \
1884 this will copy the reference instead of cloning the inner type",
1886 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1887 let mut ty = innermost;
1889 while let ty::Ref(_, inner, _) = ty.kind {
1893 let refs: String = iter::repeat('&').take(n + 1).collect();
1894 let derefs: String = iter::repeat('*').take(n).collect();
1895 let explicit = format!("{}{}::clone({})", refs, ty, snip);
1898 "try dereferencing it",
1899 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1900 Applicability::MaybeIncorrect,
1904 "or try being explicit about what type to clone",
1906 Applicability::MaybeIncorrect,
1911 return; // don't report clone_on_copy
1915 if is_copy(cx, ty) {
1917 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1918 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
1919 match &cx.tcx.hir().get(parent) {
1920 hir::Node::Expr(parent) => match parent.kind {
1921 // &*x is a nop, &x.clone() is not
1922 hir::ExprKind::AddrOf(..) |
1923 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1924 hir::ExprKind::MethodCall(..) => return,
1927 hir::Node::Stmt(stmt) => {
1928 if let hir::StmtKind::Local(ref loc) = stmt.kind {
1929 if let hir::PatKind::Ref(..) = loc.pat.kind {
1930 // let ref y = *x borrows x, let ref y = x.clone() does not
1938 // x.clone() might have dereferenced x, possibly through Deref impls
1939 if cx.tables.expr_ty(arg) == ty {
1940 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1942 let deref_count = cx
1944 .expr_adjustments(arg)
1947 if let ty::adjustment::Adjust::Deref(_) = adj.kind {
1954 let derefs: String = iter::repeat('*').take(deref_count).collect();
1955 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
1960 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1961 if let Some((text, snip)) = snip {
1962 db.span_suggestion(expr.span, text, snip, Applicability::Unspecified);
1968 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
1969 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1971 if let ty::Adt(_, subst) = obj_ty.kind {
1972 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1974 } else if match_type(cx, obj_ty, &paths::ARC) {
1976 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1986 "using `.clone()` on a ref-counted pointer",
1989 "{}::<{}>::clone(&{})",
1992 snippet(cx, arg.span, "_")
1994 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
1999 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2001 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2002 let target = &arglists[0][0];
2003 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
2004 let ref_str = if self_ty.kind == ty::Str {
2006 } else if match_type(cx, self_ty, &paths::STRING) {
2012 let mut applicability = Applicability::MachineApplicable;
2015 STRING_EXTEND_CHARS,
2017 "calling `.extend(_.chars())`",
2020 "{}.push_str({}{})",
2021 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
2023 snippet_with_applicability(cx, target.span, "_", &mut applicability)
2030 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2031 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
2032 if match_type(cx, obj_ty, &paths::STRING) {
2033 lint_string_extend(cx, expr, args);
2037 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2039 let source_type = cx.tables.expr_ty(source);
2040 if let ty::Adt(def, substs) = source_type.kind;
2041 if match_def_path(cx, def.did, &paths::RESULT);
2042 if match_type(cx, substs.type_at(0), &paths::CSTRING);
2046 TEMPORARY_CSTRING_AS_PTR,
2048 "you are getting the inner pointer of a temporary `CString`",
2050 db.note("that pointer will be invalid outside this expression");
2051 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2057 fn lint_iter_cloned_collect<'a, 'tcx>(
2058 cx: &LateContext<'a, 'tcx>,
2059 expr: &hir::Expr<'_>,
2060 iter_args: &'tcx [hir::Expr<'_>],
2063 if is_type_diagnostic_item(cx, cx.tables.expr_ty(expr), Symbol::intern("vec_type"));
2064 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0]));
2065 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2070 ITER_CLONED_COLLECT,
2072 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2075 ".to_vec()".to_string(),
2076 Applicability::MachineApplicable,
2082 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2083 fn check_fold_with_op(
2084 cx: &LateContext<'_, '_>,
2085 expr: &hir::Expr<'_>,
2086 fold_args: &[hir::Expr<'_>],
2089 replacement_method_name: &str,
2090 replacement_has_args: bool,
2093 // Extract the body of the closure passed to fold
2094 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2095 let closure_body = cx.tcx.hir().body(body_id);
2096 let closure_expr = remove_blocks(&closure_body.value);
2098 // Check if the closure body is of the form `acc <op> some_expr(x)`
2099 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2100 if bin_op.node == op;
2102 // Extract the names of the two arguments to the closure
2103 if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2104 if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2106 if match_var(&*left_expr, first_arg_ident);
2107 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2110 let mut applicability = Applicability::MachineApplicable;
2111 let sugg = if replacement_has_args {
2113 "{replacement}(|{s}| {r})",
2114 replacement = replacement_method_name,
2115 s = second_arg_ident,
2116 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2121 replacement = replacement_method_name,
2128 fold_span.with_hi(expr.span.hi()),
2129 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2130 "this `.fold` can be written more succinctly using another method",
2139 // Check that this is a call to Iterator::fold rather than just some function called fold
2140 if !match_trait_method(cx, expr, &paths::ITERATOR) {
2145 fold_args.len() == 3,
2146 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2149 // Check if the first argument to .fold is a suitable literal
2150 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2152 ast::LitKind::Bool(false) => {
2153 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2155 ast::LitKind::Bool(true) => {
2156 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2158 ast::LitKind::Int(0, _) => {
2159 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2161 ast::LitKind::Int(1, _) => {
2162 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2169 fn lint_step_by<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2170 if match_trait_method(cx, expr, &paths::ITERATOR) {
2171 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
2174 ITERATOR_STEP_BY_ZERO,
2176 "Iterator::step_by(0) will panic at runtime",
2182 fn lint_iter_nth<'a, 'tcx>(
2183 cx: &LateContext<'a, 'tcx>,
2184 expr: &hir::Expr<'_>,
2185 nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2188 let iter_args = nth_and_iter_args[1];
2189 let mut_str = if is_mut { "_mut" } else { "" };
2190 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
2192 } else if is_type_diagnostic_item(cx, cx.tables.expr_ty(&iter_args[0]), Symbol::intern("vec_type")) {
2194 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
2197 let nth_args = nth_and_iter_args[0];
2198 lint_iter_nth_zero(cx, expr, &nth_args);
2199 return; // caller is not a type that we want to lint
2206 &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2207 &format!("calling `.get{}()` is both faster and more readable", mut_str),
2211 fn lint_iter_nth_zero<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2213 if match_trait_method(cx, expr, &paths::ITERATOR);
2214 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &nth_args[1]);
2216 let mut applicability = Applicability::MachineApplicable;
2221 "called `.nth(0)` on a `std::iter::Iterator`",
2223 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2230 fn lint_get_unwrap<'a, 'tcx>(
2231 cx: &LateContext<'a, 'tcx>,
2232 expr: &hir::Expr<'_>,
2233 get_args: &'tcx [hir::Expr<'_>],
2236 // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2237 // because they do not implement `IndexMut`
2238 let mut applicability = Applicability::MachineApplicable;
2239 let expr_ty = cx.tables.expr_ty(&get_args[0]);
2240 let get_args_str = if get_args.len() > 1 {
2241 snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
2243 return; // not linting on a .get().unwrap() chain or variant
2246 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2247 needs_ref = get_args_str.parse::<usize>().is_ok();
2249 } else if is_type_diagnostic_item(cx, expr_ty, Symbol::intern("vec_type")) {
2250 needs_ref = get_args_str.parse::<usize>().is_ok();
2252 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
2253 needs_ref = get_args_str.parse::<usize>().is_ok();
2255 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
2258 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2262 return; // caller is not a type that we want to lint
2265 let mut span = expr.span;
2267 // Handle the case where the result is immediately dereferenced
2268 // by not requiring ref and pulling the dereference into the
2272 if let Some(parent) = get_parent_expr(cx, expr);
2273 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2280 let mut_str = if is_mut { "_mut" } else { "" };
2281 let borrow_str = if !needs_ref {
2294 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2295 mut_str, caller_type
2301 snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
2308 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
2309 // lint if caller of skip is an Iterator
2310 if match_trait_method(cx, expr, &paths::ITERATOR) {
2315 "called `skip(x).next()` on an iterator",
2316 "this is more succinctly expressed by calling `nth(x)`",
2321 fn derefs_to_slice<'a, 'tcx>(
2322 cx: &LateContext<'a, 'tcx>,
2323 expr: &'tcx hir::Expr<'tcx>,
2325 ) -> Option<&'tcx hir::Expr<'tcx>> {
2326 fn may_slice<'a>(cx: &LateContext<'_, 'a>, ty: Ty<'a>) -> bool {
2328 ty::Slice(_) => true,
2329 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2330 ty::Adt(..) => is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type")),
2331 ty::Array(_, size) => {
2332 if let Some(size) = size.try_eval_usize(cx.tcx, cx.param_env) {
2338 ty::Ref(_, inner, _) => may_slice(cx, inner),
2343 if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
2344 if path.ident.name == sym!(iter) && may_slice(cx, cx.tables.expr_ty(&args[0])) {
2351 ty::Slice(_) => Some(expr),
2352 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2353 ty::Ref(_, inner, _) => {
2354 if may_slice(cx, inner) {
2365 /// lint use of `unwrap()` for `Option`s and `Result`s
2366 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2367 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
2369 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
2370 Some((OPTION_UNWRAP_USED, "an Option", "None"))
2371 } else if match_type(cx, obj_ty, &paths::RESULT) {
2372 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
2377 if let Some((lint, kind, none_value)) = mess {
2382 &format!("used `unwrap()` on `{}` value", kind,),
2384 "if you don't want to handle the `{}` case gracefully, consider \
2385 using `expect()` to provide a better panic message",
2392 /// lint use of `expect()` for `Option`s and `Result`s
2393 fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2394 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&expect_args[0]));
2396 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
2397 Some((OPTION_EXPECT_USED, "an Option", "None"))
2398 } else if match_type(cx, obj_ty, &paths::RESULT) {
2399 Some((RESULT_EXPECT_USED, "a Result", "Err"))
2404 if let Some((lint, kind, none_value)) = mess {
2409 &format!("used `expect()` on `{}` value", kind,),
2410 &format!("if this value is an `{}`, it will panic", none_value,),
2415 /// lint use of `ok().expect()` for `Result`s
2416 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2418 // lint if the caller of `ok()` is a `Result`
2419 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT);
2420 let result_type = cx.tables.expr_ty(&ok_args[0]);
2421 if let Some(error_type) = get_error_type(cx, result_type);
2422 if has_debug_impl(error_type, cx);
2429 "called `ok().expect()` on a `Result` value",
2430 "you can call `expect()` directly on the `Result`",
2436 /// lint use of `map().flatten()` for `Iterators`
2437 fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2438 // lint if caller of `.map().flatten()` is an Iterator
2439 if match_trait_method(cx, expr, &paths::ITERATOR) {
2440 let msg = "called `map(..).flatten()` on an `Iterator`. \
2441 This is more succinctly expressed by calling `.flat_map(..)`";
2442 let self_snippet = snippet(cx, map_args[0].span, "..");
2443 let func_snippet = snippet(cx, map_args[1].span, "..");
2444 let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
2450 "try using `flat_map` instead",
2452 Applicability::MachineApplicable,
2457 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2458 fn lint_map_unwrap_or_else<'a, 'tcx>(
2459 cx: &LateContext<'a, 'tcx>,
2460 expr: &'tcx hir::Expr<'_>,
2461 map_args: &'tcx [hir::Expr<'_>],
2462 unwrap_args: &'tcx [hir::Expr<'_>],
2464 // lint if the caller of `map()` is an `Option`
2465 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
2466 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
2468 if is_option || is_result {
2469 // Don't make a suggestion that may fail to compile due to mutably borrowing
2470 // the same variable twice.
2471 let map_mutated_vars = mutated_variables(&map_args[0], cx);
2472 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2473 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2474 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2482 let msg = if is_option {
2483 "called `map(f).unwrap_or_else(g)` on an `Option` value. This can be done more directly by calling \
2484 `map_or_else(g, f)` instead"
2486 "called `map(f).unwrap_or_else(g)` on a `Result` value. This can be done more directly by calling \
2487 `.map_or_else(g, f)` instead"
2489 // get snippets for args to map() and unwrap_or_else()
2490 let map_snippet = snippet(cx, map_args[1].span, "..");
2491 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2492 // lint, with note if neither arg is > 1 line and both map() and
2493 // unwrap_or_else() have the same span
2494 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2495 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2496 if same_span && !multiline {
2500 OPTION_MAP_UNWRAP_OR_ELSE
2502 RESULT_MAP_UNWRAP_OR_ELSE
2508 "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
2509 map_snippet, unwrap_snippet,
2512 } else if same_span && multiline {
2516 OPTION_MAP_UNWRAP_OR_ELSE
2518 RESULT_MAP_UNWRAP_OR_ELSE
2527 /// lint use of `_.map_or(None, _)` for `Option`s
2528 fn lint_map_or_none<'a, 'tcx>(
2529 cx: &LateContext<'a, 'tcx>,
2530 expr: &'tcx hir::Expr<'_>,
2531 map_or_args: &'tcx [hir::Expr<'_>],
2533 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
2534 // check if the first non-self argument to map_or() is None
2535 let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2536 match_qpath(qpath, &paths::OPTION_NONE)
2541 if map_or_arg_is_none {
2543 let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \
2544 `and_then(f)` instead";
2545 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
2546 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
2547 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
2553 "try using `and_then` instead",
2555 Applicability::MachineApplicable,
2561 /// Lint use of `_.and_then(|x| Some(y))` for `Option`s
2562 fn lint_option_and_then_some(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2563 const LINT_MSG: &str = "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`";
2564 const NO_OP_MSG: &str = "using `Option.and_then(Some)`, which is a no-op";
2566 let ty = cx.tables.expr_ty(&args[0]);
2567 if !match_type(cx, ty, &paths::OPTION) {
2571 match args[1].kind {
2572 hir::ExprKind::Closure(_, _, body_id, closure_args_span, _) => {
2573 let closure_body = cx.tcx.hir().body(body_id);
2574 let closure_expr = remove_blocks(&closure_body.value);
2576 if let hir::ExprKind::Call(ref some_expr, ref some_args) = closure_expr.kind;
2577 if let hir::ExprKind::Path(ref qpath) = some_expr.kind;
2578 if match_qpath(qpath, &paths::OPTION_SOME);
2579 if some_args.len() == 1;
2581 let inner_expr = &some_args[0];
2583 if contains_return(inner_expr) {
2587 let some_inner_snip = if inner_expr.span.from_expansion() {
2588 snippet_with_macro_callsite(cx, inner_expr.span, "_")
2590 snippet(cx, inner_expr.span, "_")
2593 let closure_args_snip = snippet(cx, closure_args_span, "..");
2594 let option_snip = snippet(cx, args[0].span, "..");
2595 let note = format!("{}.map({} {})", option_snip, closure_args_snip, some_inner_snip);
2598 OPTION_AND_THEN_SOME,
2603 Applicability::MachineApplicable,
2608 // `_.and_then(Some)` case, which is no-op.
2609 hir::ExprKind::Path(ref qpath) => {
2610 if match_qpath(qpath, &paths::OPTION_SOME) {
2611 let option_snip = snippet(cx, args[0].span, "..");
2612 let note = format!("{}", option_snip);
2615 OPTION_AND_THEN_SOME,
2618 "use the expression directly",
2620 Applicability::MachineApplicable,
2628 /// lint use of `filter().next()` for `Iterators`
2629 fn lint_filter_next<'a, 'tcx>(
2630 cx: &LateContext<'a, 'tcx>,
2631 expr: &'tcx hir::Expr<'_>,
2632 filter_args: &'tcx [hir::Expr<'_>],
2634 // lint if caller of `.filter().next()` is an Iterator
2635 if match_trait_method(cx, expr, &paths::ITERATOR) {
2636 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2637 `.find(p)` instead.";
2638 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2639 if filter_snippet.lines().count() <= 1 {
2640 // add note if not multi-line
2647 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2650 span_lint(cx, FILTER_NEXT, expr.span, msg);
2655 /// lint use of `skip_while().next()` for `Iterators`
2656 fn lint_skip_while_next<'a, 'tcx>(
2657 cx: &LateContext<'a, 'tcx>,
2658 expr: &'tcx hir::Expr<'_>,
2659 _skip_while_args: &'tcx [hir::Expr<'_>],
2661 // lint if caller of `.skip_while().next()` is an Iterator
2662 if match_trait_method(cx, expr, &paths::ITERATOR) {
2667 "called `skip_while(p).next()` on an `Iterator`",
2668 "this is more succinctly expressed by calling `.find(!p)` instead",
2673 /// lint use of `filter().map()` for `Iterators`
2674 fn lint_filter_map<'a, 'tcx>(
2675 cx: &LateContext<'a, 'tcx>,
2676 expr: &'tcx hir::Expr<'_>,
2677 _filter_args: &'tcx [hir::Expr<'_>],
2678 _map_args: &'tcx [hir::Expr<'_>],
2680 // lint if caller of `.filter().map()` is an Iterator
2681 if match_trait_method(cx, expr, &paths::ITERATOR) {
2682 let msg = "called `filter(p).map(q)` on an `Iterator`";
2683 let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2684 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2688 /// lint use of `filter_map().next()` for `Iterators`
2689 fn lint_filter_map_next<'a, 'tcx>(
2690 cx: &LateContext<'a, 'tcx>,
2691 expr: &'tcx hir::Expr<'_>,
2692 filter_args: &'tcx [hir::Expr<'_>],
2694 if match_trait_method(cx, expr, &paths::ITERATOR) {
2695 let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2696 `.find_map(p)` instead.";
2697 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2698 if filter_snippet.lines().count() <= 1 {
2705 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2708 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2713 /// lint use of `find().map()` for `Iterators`
2714 fn lint_find_map<'a, 'tcx>(
2715 cx: &LateContext<'a, 'tcx>,
2716 expr: &'tcx hir::Expr<'_>,
2717 _find_args: &'tcx [hir::Expr<'_>],
2718 map_args: &'tcx [hir::Expr<'_>],
2720 // lint if caller of `.filter().map()` is an Iterator
2721 if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2722 let msg = "called `find(p).map(q)` on an `Iterator`";
2723 let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2724 span_lint_and_help(cx, FIND_MAP, expr.span, msg, hint);
2728 /// lint use of `filter_map().map()` for `Iterators`
2729 fn lint_filter_map_map<'a, 'tcx>(
2730 cx: &LateContext<'a, 'tcx>,
2731 expr: &'tcx hir::Expr<'_>,
2732 _filter_args: &'tcx [hir::Expr<'_>],
2733 _map_args: &'tcx [hir::Expr<'_>],
2735 // lint if caller of `.filter().map()` is an Iterator
2736 if match_trait_method(cx, expr, &paths::ITERATOR) {
2737 let msg = "called `filter_map(p).map(q)` on an `Iterator`";
2738 let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2739 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2743 /// lint use of `filter().flat_map()` for `Iterators`
2744 fn lint_filter_flat_map<'a, 'tcx>(
2745 cx: &LateContext<'a, 'tcx>,
2746 expr: &'tcx hir::Expr<'_>,
2747 _filter_args: &'tcx [hir::Expr<'_>],
2748 _map_args: &'tcx [hir::Expr<'_>],
2750 // lint if caller of `.filter().flat_map()` is an Iterator
2751 if match_trait_method(cx, expr, &paths::ITERATOR) {
2752 let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
2753 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2754 and filtering by returning `iter::empty()`";
2755 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2759 /// lint use of `filter_map().flat_map()` for `Iterators`
2760 fn lint_filter_map_flat_map<'a, 'tcx>(
2761 cx: &LateContext<'a, 'tcx>,
2762 expr: &'tcx hir::Expr<'_>,
2763 _filter_args: &'tcx [hir::Expr<'_>],
2764 _map_args: &'tcx [hir::Expr<'_>],
2766 // lint if caller of `.filter_map().flat_map()` is an Iterator
2767 if match_trait_method(cx, expr, &paths::ITERATOR) {
2768 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
2769 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2770 and filtering by returning `iter::empty()`";
2771 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2775 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2776 fn lint_flat_map_identity<'a, 'tcx>(
2777 cx: &LateContext<'a, 'tcx>,
2778 expr: &'tcx hir::Expr<'_>,
2779 flat_map_args: &'tcx [hir::Expr<'_>],
2780 flat_map_span: Span,
2782 if match_trait_method(cx, expr, &paths::ITERATOR) {
2783 let arg_node = &flat_map_args[1].kind;
2785 let apply_lint = |message: &str| {
2789 flat_map_span.with_hi(expr.span.hi()),
2792 "flatten()".to_string(),
2793 Applicability::MachineApplicable,
2798 if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
2799 let body = cx.tcx.hir().body(*body_id);
2801 if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
2802 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
2804 if path.segments.len() == 1;
2805 if path.segments[0].ident.as_str() == binding_ident.as_str();
2808 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
2813 if let hir::ExprKind::Path(ref qpath) = arg_node;
2815 if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2818 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
2824 /// lint searching an Iterator followed by `is_some()`
2825 fn lint_search_is_some<'a, 'tcx>(
2826 cx: &LateContext<'a, 'tcx>,
2827 expr: &'tcx hir::Expr<'_>,
2828 search_method: &str,
2829 search_args: &'tcx [hir::Expr<'_>],
2830 is_some_args: &'tcx [hir::Expr<'_>],
2833 // lint if caller of search is an Iterator
2834 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2836 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2837 expressed by calling `any()`.",
2840 let search_snippet = snippet(cx, search_args[1].span, "..");
2841 if search_snippet.lines().count() <= 1 {
2842 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2843 // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
2844 let any_search_snippet = if_chain! {
2845 if search_method == "find";
2846 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
2847 let closure_body = cx.tcx.hir().body(body_id);
2848 if let Some(closure_arg) = closure_body.params.get(0);
2850 if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
2851 Some(search_snippet.replacen('&', "", 1))
2852 } else if let Some(name) = get_arg_name(&closure_arg.pat) {
2853 Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
2861 // add note if not multi-line
2865 method_span.with_hi(expr.span.hi()),
2870 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2872 Applicability::MachineApplicable,
2875 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2880 /// Used for `lint_binary_expr_with_method_call`.
2881 #[derive(Copy, Clone)]
2882 struct BinaryExprInfo<'a> {
2883 expr: &'a hir::Expr<'a>,
2884 chain: &'a hir::Expr<'a>,
2885 other: &'a hir::Expr<'a>,
2889 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2890 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
2891 macro_rules! lint_with_both_lhs_and_rhs {
2892 ($func:ident, $cx:expr, $info:ident) => {
2893 if !$func($cx, $info) {
2894 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2895 if $func($cx, $info) {
2902 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2903 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2904 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2905 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2908 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2910 cx: &LateContext<'_, '_>,
2911 info: &BinaryExprInfo<'_>,
2912 chain_methods: &[&str],
2913 lint: &'static Lint,
2917 if let Some(args) = method_chain_args(info.chain, chain_methods);
2918 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2919 if arg_char.len() == 1;
2920 if let hir::ExprKind::Path(ref qpath) = fun.kind;
2921 if let Some(segment) = single_segment_path(qpath);
2922 if segment.ident.name == sym!(Some);
2924 let mut applicability = Applicability::MachineApplicable;
2925 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
2927 if self_ty.kind != ty::Str {
2935 &format!("you should use the `{}` method", suggest),
2937 format!("{}{}.{}({})",
2938 if info.eq { "" } else { "!" },
2939 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2941 snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
2952 /// Checks for the `CHARS_NEXT_CMP` lint.
2953 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2954 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2957 /// Checks for the `CHARS_LAST_CMP` lint.
2958 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2959 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2962 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2966 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2967 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
2968 cx: &LateContext<'a, 'tcx>,
2969 info: &BinaryExprInfo<'_>,
2970 chain_methods: &[&str],
2971 lint: &'static Lint,
2975 if let Some(args) = method_chain_args(info.chain, chain_methods);
2976 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2977 if let ast::LitKind::Char(c) = lit.node;
2979 let mut applicability = Applicability::MachineApplicable;
2984 &format!("you should use the `{}` method", suggest),
2986 format!("{}{}.{}('{}')",
2987 if info.eq { "" } else { "!" },
2988 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
3001 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
3002 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3003 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3006 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3007 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3008 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3011 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3015 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3016 fn lint_single_char_pattern<'a, 'tcx>(
3017 cx: &LateContext<'a, 'tcx>,
3018 _expr: &'tcx hir::Expr<'_>,
3019 arg: &'tcx hir::Expr<'_>,
3022 if let hir::ExprKind::Lit(lit) = &arg.kind;
3023 if let ast::LitKind::Str(r, style) = lit.node;
3024 if r.as_str().len() == 1;
3026 let mut applicability = Applicability::MachineApplicable;
3027 let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
3028 let ch = if let ast::StrStyle::Raw(nhash) = style {
3029 let nhash = nhash as usize;
3030 // for raw string: r##"a"##
3031 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3033 // for regular string: "a"
3034 &snip[1..(snip.len() - 1)]
3036 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3039 SINGLE_CHAR_PATTERN,
3041 "single-character string constant used as pattern",
3042 "try using a `char` instead",
3050 /// Checks for the `USELESS_ASREF` lint.
3051 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3052 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3053 // check if the call is to the actual `AsRef` or `AsMut` trait
3054 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3055 // check if the type after `as_ref` or `as_mut` is the same as before
3056 let recvr = &as_ref_args[0];
3057 let rcv_ty = cx.tables.expr_ty(recvr);
3058 let res_ty = cx.tables.expr_ty(expr);
3059 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3060 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3061 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3062 // allow the `as_ref` or `as_mut` if it is followed by another method call
3064 if let Some(parent) = get_parent_expr(cx, expr);
3065 if let hir::ExprKind::MethodCall(_, ref span, _) = parent.kind;
3066 if span != &expr.span;
3072 let mut applicability = Applicability::MachineApplicable;
3077 &format!("this call to `{}` does nothing", call_name),
3079 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
3086 fn ty_has_iter_method(cx: &LateContext<'_, '_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3087 has_iter_method(cx, self_ref_ty).map(|ty_name| {
3088 let mutbl = match self_ref_ty.kind {
3089 ty::Ref(_, _, mutbl) => mutbl,
3090 _ => unreachable!(),
3092 let method_name = match mutbl {
3093 hir::Mutability::Not => "iter",
3094 hir::Mutability::Mut => "iter_mut",
3096 (ty_name, method_name)
3100 fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3101 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3104 if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3110 "this `.into_iter()` call is equivalent to `.{}()` and will not move the `{}`",
3114 method_name.to_string(),
3115 Applicability::MachineApplicable,
3120 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3121 fn lint_maybe_uninit(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3123 if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3125 if let hir::ExprKind::Path(ref path) = callee.kind;
3126 if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3127 if !is_maybe_uninit_ty_valid(cx, cx.tables.expr_ty_adjusted(outer));
3131 UNINIT_ASSUMED_INIT,
3133 "this call for this type may be undefined behavior"
3139 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
3141 ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3142 ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3143 ty::Adt(ref adt, _) => {
3144 // needs to be a MaybeUninit
3145 match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT)
3151 fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
3156 "this call to `map()` won't have an effect on the call to `count()`",
3157 "make sure you did not confuse `map` with `filter` or `for_each`",
3161 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3162 fn lint_option_as_ref_deref<'a, 'tcx>(
3163 cx: &LateContext<'a, 'tcx>,
3164 expr: &hir::Expr<'_>,
3165 as_ref_args: &[hir::Expr<'_>],
3166 map_args: &[hir::Expr<'_>],
3169 let option_ty = cx.tables.expr_ty(&as_ref_args[0]);
3170 if !match_type(cx, option_ty, &paths::OPTION) {
3174 let deref_aliases: [&[&str]; 9] = [
3175 &paths::DEREF_TRAIT_METHOD,
3176 &paths::DEREF_MUT_TRAIT_METHOD,
3177 &paths::CSTRING_AS_C_STR,
3178 &paths::OS_STRING_AS_OS_STR,
3179 &paths::PATH_BUF_AS_PATH,
3180 &paths::STRING_AS_STR,
3181 &paths::STRING_AS_MUT_STR,
3182 &paths::VEC_AS_SLICE,
3183 &paths::VEC_AS_MUT_SLICE,
3186 let is_deref = match map_args[1].kind {
3187 hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3188 hir::ExprKind::Closure(_, _, body_id, _, _) => {
3189 let closure_body = cx.tcx.hir().body(body_id);
3190 let closure_expr = remove_blocks(&closure_body.value);
3192 if let hir::ExprKind::MethodCall(_, _, args) = &closure_expr.kind;
3194 if let hir::ExprKind::Path(qpath) = &args[0].kind;
3195 if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id);
3196 if closure_body.params[0].pat.hir_id == local_id;
3197 let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::<Box<[_]>>();
3198 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3200 let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap();
3201 deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3212 let current_method = if is_mut {
3213 ".as_mut().map(DerefMut::deref_mut)"
3215 ".as_ref().map(Deref::deref)"
3217 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3218 let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3219 let suggestion = format!("try using {} instead", method_hint);
3222 "called `{0}` (or with one of deref aliases) on an Option value. \
3223 This can be done more directly by calling `{1}` instead",
3224 current_method, hint
3228 OPTION_AS_REF_DEREF,
3233 Applicability::MachineApplicable,
3238 /// Given a `Result<T, E>` type, return its error type (`E`).
3239 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3241 ty::Adt(_, substs) if match_type(cx, ty, &paths::RESULT) => substs.types().nth(1),
3246 /// This checks whether a given type is known to implement Debug.
3247 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
3249 .get_diagnostic_item(sym::debug_trait)
3250 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3255 StartsWith(&'static str),
3259 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3260 (Convention::Eq("new"), &[SelfKind::No]),
3261 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3262 (Convention::StartsWith("from_"), &[SelfKind::No]),
3263 (Convention::StartsWith("into_"), &[SelfKind::Value]),
3264 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3265 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3266 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3270 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
3271 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
3272 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
3273 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
3274 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
3275 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
3276 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
3277 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
3278 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
3279 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
3280 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
3281 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
3282 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
3283 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
3284 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
3285 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
3286 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
3287 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
3288 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
3289 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
3290 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
3291 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
3292 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
3293 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
3294 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
3295 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
3296 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
3297 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
3298 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
3299 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
3300 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
3304 const PATTERN_METHODS: [(&str, usize); 17] = [
3312 ("split_terminator", 1),
3313 ("rsplit_terminator", 1),
3318 ("match_indices", 1),
3319 ("rmatch_indices", 1),
3320 ("trim_start_matches", 1),
3321 ("trim_end_matches", 1),
3324 #[derive(Clone, Copy, PartialEq, Debug)]
3333 fn matches<'a>(self, cx: &LateContext<'_, 'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3334 fn matches_value(parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3335 if ty == parent_ty {
3337 } else if ty.is_box() {
3338 ty.boxed_ty() == parent_ty
3339 } else if ty.is_rc() || ty.is_arc() {
3340 if let ty::Adt(_, substs) = ty.kind {
3341 substs.types().next().map_or(false, |t| t == parent_ty)
3351 cx: &LateContext<'_, 'a>,
3352 mutability: hir::Mutability,
3356 if let ty::Ref(_, t, m) = ty.kind {
3357 return m == mutability && t == parent_ty;
3360 let trait_path = match mutability {
3361 hir::Mutability::Not => &paths::ASREF_TRAIT,
3362 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3365 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3367 None => return false,
3369 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3373 Self::Value => matches_value(parent_ty, ty),
3374 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3375 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3376 Self::No => ty != parent_ty,
3381 fn description(self) -> &'static str {
3383 Self::Value => "self by value",
3384 Self::Ref => "self by reference",
3385 Self::RefMut => "self by mutable reference",
3386 Self::No => "no self",
3393 fn check(&self, other: &str) -> bool {
3395 Self::Eq(this) => this == other,
3396 Self::StartsWith(this) => other.starts_with(this) && this != other,
3401 impl fmt::Display for Convention {
3402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3404 Self::Eq(this) => this.fmt(f),
3405 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3410 #[derive(Clone, Copy)]
3419 fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FnRetTy<'_>) -> bool {
3420 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3422 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3423 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3424 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3425 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3426 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3432 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3433 if let hir::TyKind::Path(ref p) = ty.kind {
3434 match_qpath(p, &["bool"])
3440 // Returns `true` if `expr` contains a return expression
3441 fn contains_return(expr: &hir::Expr<'_>) -> bool {
3442 struct RetCallFinder {
3446 impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
3447 type Map = Map<'tcx>;
3449 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
3453 if let hir::ExprKind::Ret(..) = &expr.kind {
3456 intravisit::walk_expr(self, expr);
3460 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
3461 intravisit::NestedVisitorMap::None
3465 let mut visitor = RetCallFinder { found: false };
3466 visitor.visit_expr(expr);
3470 fn check_pointer_offset(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3473 if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.tables.expr_ty(&args[0]).kind;
3474 if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3477 span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3482 fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3483 let ty = cx.tables.expr_ty(&args[0]);
3485 if !match_type(cx, ty, &paths::FILE_TYPE) {
3491 let lint_unary: &str;
3492 let help_unary: &str;
3494 if let Some(parent) = get_parent_expr(cx, expr);
3495 if let hir::ExprKind::Unary(op, _) = parent.kind;
3496 if op == hir::UnOp::UnNot;
3509 let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3510 let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3511 span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, &help_msg);