1 mod bind_instead_of_map;
2 mod inefficient_to_string;
3 mod manual_saturating_arithmetic;
4 mod option_map_unwrap_or;
5 mod unnecessary_filter_map;
11 use bind_instead_of_map::BindInsteadOfMap;
12 use if_chain::if_chain;
14 use rustc_errors::Applicability;
16 use rustc_hir::intravisit::{self, Visitor};
17 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::lint::in_external_macro;
20 use rustc_middle::ty::subst::GenericArgKind;
21 use rustc_middle::ty::{self, Ty};
22 use rustc_session::{declare_lint_pass, declare_tool_lint};
23 use rustc_span::source_map::Span;
24 use rustc_span::symbol::{sym, SymbolStr};
26 use crate::consts::{constant, Constant};
27 use crate::utils::usage::mutated_variables;
29 get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, implements_trait, in_macro, is_copy,
30 is_ctor_or_promotable_const_function, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
31 match_def_path, match_qpath, match_trait_method, match_type, match_var, method_calls, method_chain_args, paths,
32 remove_blocks, return_ty, same_tys, single_segment_path, snippet, snippet_with_applicability,
33 snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
34 span_lint_and_then, sugg, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
37 declare_clippy_lint! {
38 /// **What it does:** Checks for `.unwrap()` calls on `Option`s and on `Result`s.
40 /// **Why is this bad?** It is better to handle the `None` or `Err` case,
41 /// or at least call `.expect(_)` with a more helpful message. Still, for a lot of
42 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
43 /// `Allow` by default.
45 /// `result.unwrap()` will let the thread panic on `Err` values.
46 /// Normally, you want to implement more sophisticated error handling,
47 /// and propagate errors upwards with `?` operator.
49 /// Even if you want to panic on errors, not all `Error`s implement good
50 /// messages on display. Therefore, it may be beneficial to look at the places
51 /// where they may get displayed. Activate this lint to do just that.
53 /// **Known problems:** None.
57 /// # let opt = Some(1);
63 /// opt.expect("more helpful message");
69 /// # let res: Result<usize, ()> = Ok(1);
75 /// res.expect("more helpful message");
79 "using `.unwrap()` on `Result` or `Option`, which should at least get a better message using `expect()`"
82 declare_clippy_lint! {
83 /// **What it does:** Checks for `.expect()` calls on `Option`s and `Result`s.
85 /// **Why is this bad?** Usually it is better to handle the `None` or `Err` case.
86 /// Still, for a lot of quick-and-dirty code, `expect` is a good choice, which is why
87 /// this lint is `Allow` by default.
89 /// `result.expect()` will let the thread panic on `Err`
90 /// values. Normally, you want to implement more sophisticated error handling,
91 /// and propagate errors upwards with `?` operator.
93 /// **Known problems:** None.
97 /// # let opt = Some(1);
100 /// opt.expect("one");
103 /// let opt = Some(1);
110 /// # let res: Result<usize, ()> = Ok(1);
113 /// res.expect("one");
117 /// # Ok::<(), ()>(())
121 "using `.expect()` on `Result` or `Option`, which might be better handled"
124 declare_clippy_lint! {
125 /// **What it does:** Checks for methods that should live in a trait
126 /// implementation of a `std` trait (see [llogiq's blog
127 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
128 /// information) instead of an inherent implementation.
130 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
131 /// the code, often with very little cost. Also people seeing a `mul(...)`
133 /// may expect `*` to work equally, so you should have good reason to disappoint
136 /// **Known problems:** None.
142 /// fn add(&self, other: &X) -> X {
148 pub SHOULD_IMPLEMENT_TRAIT,
150 "defining a method that should be implementing a std trait"
153 declare_clippy_lint! {
154 /// **What it does:** Checks for methods with certain name prefixes and which
155 /// doesn't match how self is taken. The actual rules are:
157 /// |Prefix |`self` taken |
158 /// |-------|----------------------|
159 /// |`as_` |`&self` or `&mut self`|
161 /// |`into_`|`self` |
162 /// |`is_` |`&self` or none |
163 /// |`to_` |`&self` |
165 /// **Why is this bad?** Consistency breeds readability. If you follow the
166 /// conventions, your users won't be surprised that they, e.g., need to supply a
167 /// mutable reference to a `as_..` function.
169 /// **Known problems:** None.
175 /// fn as_str(self) -> &'static str {
181 pub WRONG_SELF_CONVENTION,
183 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
186 declare_clippy_lint! {
187 /// **What it does:** This is the same as
188 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
190 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
192 /// **Known problems:** Actually *renaming* the function may break clients if
193 /// the function is part of the public interface. In that case, be mindful of
194 /// the stability guarantees you've given your users.
200 /// pub fn as_str(self) -> &'a str {
205 pub WRONG_PUB_SELF_CONVENTION,
207 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
210 declare_clippy_lint! {
211 /// **What it does:** Checks for usage of `ok().expect(..)`.
213 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
214 /// directly to get a better error message.
216 /// **Known problems:** The error type needs to implement `Debug`
220 /// # let x = Ok::<_, ()>(());
221 /// x.ok().expect("why did I do this again?")
225 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
228 declare_clippy_lint! {
229 /// **What it does:** Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
230 /// `result.map(_).unwrap_or_else(_)`.
232 /// **Why is this bad?** Readability, these can be written more concisely (resp.) as
233 /// `option.map_or(_, _)`, `option.map_or_else(_, _)` and `result.map_or_else(_, _)`.
235 /// **Known problems:** The order of the arguments is not in execution order
239 /// # let x = Some(1);
242 /// x.map(|a| a + 1).unwrap_or(0);
245 /// x.map_or(0, |a| a + 1);
251 /// # let x: Result<usize, ()> = Ok(1);
252 /// # fn some_function(foo: ()) -> usize { 1 }
255 /// x.map(|a| a + 1).unwrap_or_else(some_function);
258 /// x.map_or_else(some_function, |a| a + 1);
262 "using `.map(f).unwrap_or(a)` or `.map(f).unwrap_or_else(func)`, which are more succinctly expressed as `map_or(a, f)` or `map_or_else(a, f)`"
265 declare_clippy_lint! {
266 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
268 /// **Why is this bad?** Readability, this can be written more concisely as
271 /// **Known problems:** The order of the arguments is not in execution order.
275 /// # let opt = Some(1);
276 /// opt.map_or(None, |a| Some(a + 1))
279 pub OPTION_MAP_OR_NONE,
281 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
284 declare_clippy_lint! {
285 /// **What it does:** Checks for usage of `_.map_or(None, Some)`.
287 /// **Why is this bad?** Readability, this can be written more concisely as
290 /// **Known problems:** None.
296 /// # let r: Result<u32, &str> = Ok(1);
297 /// assert_eq!(Some(1), r.map_or(None, Some));
302 /// # let r: Result<u32, &str> = Ok(1);
303 /// assert_eq!(Some(1), r.ok());
305 pub RESULT_MAP_OR_INTO_OPTION,
307 "using `Result.map_or(None, Some)`, which is more succinctly expressed as `ok()`"
310 declare_clippy_lint! {
311 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`, `_.and_then(|x| Ok(y))` or
312 /// `_.or_else(|x| Err(y))`.
314 /// **Why is this bad?** Readability, this can be written more concisely as
315 /// `_.map(|x| y)` or `_.map_err(|x| y)`.
317 /// **Known problems:** None
322 /// # fn opt() -> Option<&'static str> { Some("42") }
323 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
324 /// let _ = opt().and_then(|s| Some(s.len()));
325 /// let _ = res().and_then(|s| if s.len() == 42 { Ok(10) } else { Ok(20) });
326 /// let _ = res().or_else(|s| if s.len() == 42 { Err(10) } else { Err(20) });
329 /// The correct use would be:
332 /// # fn opt() -> Option<&'static str> { Some("42") }
333 /// # fn res() -> Result<&'static str, &'static str> { Ok("42") }
334 /// let _ = opt().map(|s| s.len());
335 /// let _ = res().map(|s| if s.len() == 42 { 10 } else { 20 });
336 /// let _ = res().map_err(|s| if s.len() == 42 { 10 } else { 20 });
338 pub BIND_INSTEAD_OF_MAP,
340 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
343 declare_clippy_lint! {
344 /// **What it does:** Checks for usage of `_.filter(_).next()`.
346 /// **Why is this bad?** Readability, this can be written more concisely as
349 /// **Known problems:** None.
353 /// # let vec = vec![1];
354 /// vec.iter().filter(|x| **x == 0).next();
356 /// Could be written as
358 /// # let vec = vec![1];
359 /// vec.iter().find(|x| **x == 0);
363 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
366 declare_clippy_lint! {
367 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
369 /// **Why is this bad?** Readability, this can be written more concisely as
370 /// `_.find(!condition)`.
372 /// **Known problems:** None.
376 /// # let vec = vec![1];
377 /// vec.iter().skip_while(|x| **x == 0).next();
379 /// Could be written as
381 /// # let vec = vec![1];
382 /// vec.iter().find(|x| **x != 0);
386 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
389 declare_clippy_lint! {
390 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
392 /// **Why is this bad?** Readability, this can be written more concisely as a
393 /// single method call.
395 /// **Known problems:**
399 /// let vec = vec![vec![1]];
400 /// vec.iter().map(|x| x.iter()).flatten();
404 "using combinations of `flatten` and `map` which can usually be written as a single method call"
407 declare_clippy_lint! {
408 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
409 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
411 /// **Why is this bad?** Readability, this can be written more concisely as a
412 /// single method call.
414 /// **Known problems:** Often requires a condition + Option/Iterator creation
415 /// inside the closure.
419 /// let vec = vec![1];
420 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
424 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
427 declare_clippy_lint! {
428 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
430 /// **Why is this bad?** Readability, this can be written more concisely as a
431 /// single method call.
433 /// **Known problems:** None
437 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
439 /// Can be written as
442 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
446 "using combination of `filter_map` and `next` which can usually be written as a single method call"
449 declare_clippy_lint! {
450 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
452 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
454 /// **Known problems:** None
458 /// # let iter = vec![vec![0]].into_iter();
459 /// iter.flat_map(|x| x);
461 /// Can be written as
463 /// # let iter = vec![vec![0]].into_iter();
466 pub FLAT_MAP_IDENTITY,
468 "call to `flat_map` where `flatten` is sufficient"
471 declare_clippy_lint! {
472 /// **What it does:** Checks for usage of `_.find(_).map(_)`.
474 /// **Why is this bad?** Readability, this can be written more concisely as a
475 /// single method call.
477 /// **Known problems:** Often requires a condition + Option/Iterator creation
478 /// inside the closure.
482 /// (0..3).find(|x| *x == 2).map(|x| x * 2);
484 /// Can be written as
486 /// (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
490 "using a combination of `find` and `map` can usually be written as a single method call"
493 declare_clippy_lint! {
494 /// **What it does:** Checks for an iterator search (such as `find()`,
495 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
497 /// **Why is this bad?** Readability, this can be written more concisely as
500 /// **Known problems:** None.
504 /// # let vec = vec![1];
505 /// vec.iter().find(|x| **x == 0).is_some();
507 /// Could be written as
509 /// # let vec = vec![1];
510 /// vec.iter().any(|x| *x == 0);
514 "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
517 declare_clippy_lint! {
518 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
519 /// if it starts with a given char.
521 /// **Why is this bad?** Readability, this can be written more concisely as
522 /// `_.starts_with(_)`.
524 /// **Known problems:** None.
528 /// let name = "foo";
529 /// if name.chars().next() == Some('_') {};
531 /// Could be written as
533 /// let name = "foo";
534 /// if name.starts_with('_') {};
538 "using `.chars().next()` to check if a string starts with a char"
541 declare_clippy_lint! {
542 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
543 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
544 /// `unwrap_or_default` instead.
546 /// **Why is this bad?** The function will always be called and potentially
547 /// allocate an object acting as the default.
549 /// **Known problems:** If the function has side-effects, not calling it will
550 /// change the semantic of the program, but you shouldn't rely on that anyway.
554 /// # let foo = Some(String::new());
555 /// foo.unwrap_or(String::new());
557 /// this can instead be written:
559 /// # let foo = Some(String::new());
560 /// foo.unwrap_or_else(String::new);
564 /// # let foo = Some(String::new());
565 /// foo.unwrap_or_default();
569 "using any `*or` method with a function call, which suggests `*or_else`"
572 declare_clippy_lint! {
573 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
574 /// etc., and suggests to use `unwrap_or_else` instead
576 /// **Why is this bad?** The function will always be called.
578 /// **Known problems:** If the function has side-effects, not calling it will
579 /// change the semantics of the program, but you shouldn't rely on that anyway.
583 /// # let foo = Some(String::new());
584 /// # let err_code = "418";
585 /// # let err_msg = "I'm a teapot";
586 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
590 /// # let foo = Some(String::new());
591 /// # let err_code = "418";
592 /// # let err_msg = "I'm a teapot";
593 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
595 /// this can instead be written:
597 /// # let foo = Some(String::new());
598 /// # let err_code = "418";
599 /// # let err_msg = "I'm a teapot";
600 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
604 "using any `expect` method with a function call"
607 declare_clippy_lint! {
608 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
610 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
611 /// generics, not for using the `clone` method on a concrete type.
613 /// **Known problems:** None.
621 "using `clone` on a `Copy` type"
624 declare_clippy_lint! {
625 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
626 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
627 /// function syntax instead (e.g., `Rc::clone(foo)`).
629 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
630 /// can obscure the fact that only the pointer is being cloned, not the underlying
635 /// # use std::rc::Rc;
636 /// let x = Rc::new(1);
639 pub CLONE_ON_REF_PTR,
641 "using 'clone' on a ref-counted pointer"
644 declare_clippy_lint! {
645 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
647 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
648 /// cloning the underlying `T`.
650 /// **Known problems:** None.
657 /// let z = y.clone();
658 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
661 pub CLONE_DOUBLE_REF,
663 "using `clone` on `&&T`"
666 declare_clippy_lint! {
667 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
668 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
670 /// **Why is this bad?** This bypasses the specialized implementation of
671 /// `ToString` and instead goes through the more expensive string formatting
674 /// **Known problems:** None.
678 /// // Generic implementation for `T: Display` is used (slow)
679 /// ["foo", "bar"].iter().map(|s| s.to_string());
681 /// // OK, the specialized impl is used
682 /// ["foo", "bar"].iter().map(|&s| s.to_string());
684 pub INEFFICIENT_TO_STRING,
686 "using `to_string` on `&&T` where `T: ToString`"
689 declare_clippy_lint! {
690 /// **What it does:** Checks for `new` not returning a type that contains `Self`.
692 /// **Why is this bad?** As a convention, `new` methods are used to make a new
693 /// instance of a type.
695 /// **Known problems:** None.
700 /// # struct NotAFoo;
702 /// fn new() -> NotAFoo {
710 /// # struct FooError;
712 /// // Good. Return type contains `Self`
713 /// fn new() -> Result<Foo, FooError> {
723 /// // Bad. The type name must contain `Self`.
724 /// fn new() -> Bar {
731 "not returning type containing `Self` in a `new` method"
734 declare_clippy_lint! {
735 /// **What it does:** Checks for string methods that receive a single-character
736 /// `str` as an argument, e.g., `_.split("x")`.
738 /// **Why is this bad?** Performing these methods using a `char` is faster than
741 /// **Known problems:** Does not catch multi-byte unicode characters.
744 /// `_.split("x")` could be `_.split('x')`
745 pub SINGLE_CHAR_PATTERN,
747 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
750 declare_clippy_lint! {
751 /// **What it does:** Checks for getting the inner pointer of a temporary
754 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
755 /// as the `CString` is alive.
757 /// **Known problems:** None.
761 /// # use std::ffi::CString;
762 /// # fn call_some_ffi_func(_: *const i8) {}
764 /// let c_str = CString::new("foo").unwrap().as_ptr();
766 /// call_some_ffi_func(c_str);
769 /// Here `c_str` point to a freed address. The correct use would be:
771 /// # use std::ffi::CString;
772 /// # fn call_some_ffi_func(_: *const i8) {}
774 /// let c_str = CString::new("foo").unwrap();
776 /// call_some_ffi_func(c_str.as_ptr());
779 pub TEMPORARY_CSTRING_AS_PTR,
781 "getting the inner pointer of a temporary `CString`"
784 declare_clippy_lint! {
785 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
787 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
788 /// actually intend to panic.
790 /// **Known problems:** None.
793 /// ```rust,should_panic
794 /// for x in (0..100).step_by(0) {
798 pub ITERATOR_STEP_BY_ZERO,
800 "using `Iterator::step_by(0)`, which will panic at runtime"
803 declare_clippy_lint! {
804 /// **What it does:** Checks for the use of `iter.nth(0)`.
806 /// **Why is this bad?** `iter.next()` is equivalent to
807 /// `iter.nth(0)`, as they both consume the next element,
808 /// but is more readable.
810 /// **Known problems:** None.
815 /// # use std::collections::HashSet;
817 /// # let mut s = HashSet::new();
819 /// let x = s.iter().nth(0);
822 /// # let mut s = HashSet::new();
824 /// let x = s.iter().next();
828 "replace `iter.nth(0)` with `iter.next()`"
831 declare_clippy_lint! {
832 /// **What it does:** Checks for use of `.iter().nth()` (and the related
833 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
835 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
838 /// **Known problems:** None.
842 /// let some_vec = vec![0, 1, 2, 3];
843 /// let bad_vec = some_vec.iter().nth(3);
844 /// let bad_slice = &some_vec[..].iter().nth(3);
846 /// The correct use would be:
848 /// let some_vec = vec![0, 1, 2, 3];
849 /// let bad_vec = some_vec.get(3);
850 /// let bad_slice = &some_vec[..].get(3);
854 "using `.iter().nth()` on a standard library type with O(1) element access"
857 declare_clippy_lint! {
858 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
860 /// **Why is this bad?** `.nth(x)` is cleaner
862 /// **Known problems:** None.
866 /// let some_vec = vec![0, 1, 2, 3];
867 /// let bad_vec = some_vec.iter().skip(3).next();
868 /// let bad_slice = &some_vec[..].iter().skip(3).next();
870 /// The correct use would be:
872 /// let some_vec = vec![0, 1, 2, 3];
873 /// let bad_vec = some_vec.iter().nth(3);
874 /// let bad_slice = &some_vec[..].iter().nth(3);
878 "using `.skip(x).next()` on an iterator"
881 declare_clippy_lint! {
882 /// **What it does:** Checks for use of `.get().unwrap()` (or
883 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
885 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
888 /// **Known problems:** Not a replacement for error handling: Using either
889 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
890 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
891 /// temporary placeholder for dealing with the `Option` type, then this does
892 /// not mitigate the need for error handling. If there is a chance that `.get()`
893 /// will be `None` in your program, then it is advisable that the `None` case
894 /// is handled in a future refactor instead of using `.unwrap()` or the Index
899 /// let mut some_vec = vec![0, 1, 2, 3];
900 /// let last = some_vec.get(3).unwrap();
901 /// *some_vec.get_mut(0).unwrap() = 1;
903 /// The correct use would be:
905 /// let mut some_vec = vec![0, 1, 2, 3];
906 /// let last = some_vec[3];
911 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
914 declare_clippy_lint! {
915 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
916 /// `&str` or `String`.
918 /// **Why is this bad?** `.push_str(s)` is clearer
920 /// **Known problems:** None.
925 /// let def = String::from("def");
926 /// let mut s = String::new();
927 /// s.extend(abc.chars());
928 /// s.extend(def.chars());
930 /// The correct use would be:
933 /// let def = String::from("def");
934 /// let mut s = String::new();
936 /// s.push_str(&def);
938 pub STRING_EXTEND_CHARS,
940 "using `x.extend(s.chars())` where s is a `&str` or `String`"
943 declare_clippy_lint! {
944 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
947 /// **Why is this bad?** `.to_vec()` is clearer
949 /// **Known problems:** None.
953 /// let s = [1, 2, 3, 4, 5];
954 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
956 /// The better use would be:
958 /// let s = [1, 2, 3, 4, 5];
959 /// let s2: Vec<isize> = s.to_vec();
961 pub ITER_CLONED_COLLECT,
963 "using `.cloned().collect()` on slice to create a `Vec`"
966 declare_clippy_lint! {
967 /// **What it does:** Checks for usage of `.chars().last()` or
968 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
970 /// **Why is this bad?** Readability, this can be written more concisely as
971 /// `_.ends_with(_)`.
973 /// **Known problems:** None.
977 /// # let name = "_";
978 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
983 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
986 declare_clippy_lint! {
987 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
988 /// types before and after the call are the same.
990 /// **Why is this bad?** The call is unnecessary.
992 /// **Known problems:** None.
996 /// # fn do_stuff(x: &[i32]) {}
997 /// let x: &[i32] = &[1, 2, 3, 4, 5];
998 /// do_stuff(x.as_ref());
1000 /// The correct use would be:
1002 /// # fn do_stuff(x: &[i32]) {}
1003 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1008 "using `as_ref` where the types before and after the call are the same"
1011 declare_clippy_lint! {
1012 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1013 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1014 /// `sum` or `product`.
1016 /// **Why is this bad?** Readability.
1018 /// **Known problems:** False positive in pattern guards. Will be resolved once
1019 /// non-lexical lifetimes are stable.
1023 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1025 /// This could be written as:
1027 /// let _ = (0..3).any(|x| x > 2);
1029 pub UNNECESSARY_FOLD,
1031 "using `fold` when a more succinct alternative exists"
1034 declare_clippy_lint! {
1035 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1036 /// More specifically it checks if the closure provided is only performing one of the
1037 /// filter or map operations and suggests the appropriate option.
1039 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1040 /// operation is being performed.
1042 /// **Known problems:** None
1046 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1048 /// As there is no transformation of the argument this could be written as:
1050 /// let _ = (0..3).filter(|&x| x > 2);
1054 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1056 /// As there is no conditional check on the argument this could be written as:
1058 /// let _ = (0..4).map(|x| x + 1);
1060 pub UNNECESSARY_FILTER_MAP,
1062 "using `filter_map` when a more succinct alternative exists"
1065 declare_clippy_lint! {
1066 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1069 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1070 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1071 /// `iter_mut` directly.
1073 /// **Known problems:** None
1078 /// let _ = (&vec![3, 4, 5]).into_iter();
1080 pub INTO_ITER_ON_REF,
1082 "using `.into_iter()` on a reference"
1085 declare_clippy_lint! {
1086 /// **What it does:** Checks for calls to `map` followed by a `count`.
1088 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1089 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1090 /// drive the iterator to completion, you can just use `for_each` instead.
1092 /// **Known problems:** None
1097 /// let _ = (0..3).map(|x| x + 2).count();
1101 "suspicious usage of map"
1104 declare_clippy_lint! {
1105 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1107 /// **Why is this bad?** For most types, this is undefined behavior.
1109 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1110 /// of `MaybeUninit`. There may be other types that allow uninitialized
1111 /// data, but those are not yet rigorously defined.
1116 /// // Beware the UB
1117 /// use std::mem::MaybeUninit;
1119 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1122 /// Note that the following is OK:
1125 /// use std::mem::MaybeUninit;
1127 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1128 /// MaybeUninit::uninit().assume_init()
1131 pub UNINIT_ASSUMED_INIT,
1133 "`MaybeUninit::uninit().assume_init()`"
1136 declare_clippy_lint! {
1137 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1139 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1144 /// # let y: u32 = 0;
1145 /// # let x: u32 = 100;
1146 /// let add = x.checked_add(y).unwrap_or(u32::MAX);
1147 /// let sub = x.checked_sub(y).unwrap_or(u32::MIN);
1150 /// can be written using dedicated methods for saturating addition/subtraction as:
1153 /// # let y: u32 = 0;
1154 /// # let x: u32 = 100;
1155 /// let add = x.saturating_add(y);
1156 /// let sub = x.saturating_sub(y);
1158 pub MANUAL_SATURATING_ARITHMETIC,
1160 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1163 declare_clippy_lint! {
1164 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1165 /// zero-sized types
1167 /// **Why is this bad?** This is a no-op, and likely unintended
1169 /// **Known problems:** None
1173 /// unsafe { (&() as *const ()).offset(1) };
1177 "Check for offset calculations on raw pointers to zero-sized types"
1180 declare_clippy_lint! {
1181 /// **What it does:** Checks for `FileType::is_file()`.
1183 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1184 /// they are testing whether a path is something they can get bytes from. But
1185 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1186 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1192 /// let metadata = std::fs::metadata("foo.txt")?;
1193 /// let filetype = metadata.file_type();
1195 /// if filetype.is_file() {
1198 /// # Ok::<_, std::io::Error>(())
1202 /// should be written as:
1206 /// let metadata = std::fs::metadata("foo.txt")?;
1207 /// let filetype = metadata.file_type();
1209 /// if !filetype.is_dir() {
1212 /// # Ok::<_, std::io::Error>(())
1215 pub FILETYPE_IS_FILE,
1217 "`FileType::is_file` is not recommended to test for readable file type"
1220 declare_clippy_lint! {
1221 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1223 /// **Why is this bad?** Readability, this can be written more concisely as a
1224 /// single method call.
1226 /// **Known problems:** None.
1230 /// # let opt = Some("".to_string());
1231 /// opt.as_ref().map(String::as_str)
1234 /// Can be written as
1236 /// # let opt = Some("".to_string());
1240 pub OPTION_AS_REF_DEREF,
1242 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1245 declare_lint_pass!(Methods => [
1248 SHOULD_IMPLEMENT_TRAIT,
1249 WRONG_SELF_CONVENTION,
1250 WRONG_PUB_SELF_CONVENTION,
1253 RESULT_MAP_OR_INTO_OPTION,
1255 BIND_INSTEAD_OF_MAP,
1263 INEFFICIENT_TO_STRING,
1265 SINGLE_CHAR_PATTERN,
1267 TEMPORARY_CSTRING_AS_PTR,
1275 ITERATOR_STEP_BY_ZERO,
1280 STRING_EXTEND_CHARS,
1281 ITER_CLONED_COLLECT,
1284 UNNECESSARY_FILTER_MAP,
1287 UNINIT_ASSUMED_INIT,
1288 MANUAL_SATURATING_ARITHMETIC,
1291 OPTION_AS_REF_DEREF,
1294 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
1295 #[allow(clippy::too_many_lines)]
1296 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
1297 if in_macro(expr.span) {
1301 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1302 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1303 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1305 match method_names.as_slice() {
1306 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1307 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1308 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1309 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1310 ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1311 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1312 ["unwrap_or_else", "map"] => lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]),
1313 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1314 ["and_then", ..] => {
1315 bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
1316 bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
1318 ["or_else", ..] => {
1319 bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]);
1321 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1322 ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1323 ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
1324 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1325 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
1326 ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
1327 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1328 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1329 ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1330 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1331 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1332 ["is_some", "position"] => {
1333 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1335 ["is_some", "rposition"] => {
1336 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1338 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1339 ["as_ptr", "unwrap"] | ["as_ptr", "expect"] => {
1340 lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0])
1342 ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1343 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1344 ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1345 ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1346 ["next", "skip"] => lint_iter_skip_next(cx, expr),
1347 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1348 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1349 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1350 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1351 ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
1352 ["count", "map"] => lint_suspicious_map(cx, expr),
1353 ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1354 ["unwrap_or", arith @ "checked_add"]
1355 | ["unwrap_or", arith @ "checked_sub"]
1356 | ["unwrap_or", arith @ "checked_mul"] => {
1357 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1359 ["add"] | ["offset"] | ["sub"] | ["wrapping_offset"] | ["wrapping_add"] | ["wrapping_sub"] => {
1360 check_pointer_offset(cx, expr, arg_lists[0])
1362 ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1363 ["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
1364 ["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
1369 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
1370 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1371 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1373 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
1374 if args.len() == 1 && method_call.ident.name == sym!(clone) {
1375 lint_clone_on_copy(cx, expr, &args[0], self_ty);
1376 lint_clone_on_ref_ptr(cx, expr, &args[0]);
1378 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1379 inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1382 match self_ty.kind {
1383 ty::Ref(_, ty, _) if ty.kind == ty::Str => {
1384 for &(method, pos) in &PATTERN_METHODS {
1385 if method_call.ident.name.as_str() == method && args.len() > pos {
1386 lint_single_char_pattern(cx, expr, &args[pos]);
1390 ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
1391 lint_into_iter(cx, expr, self_ty, *method_span);
1396 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1397 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1399 let mut info = BinaryExprInfo {
1403 eq: op.node == hir::BinOpKind::Eq,
1405 lint_binary_expr_with_method_call(cx, &mut info);
1411 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1412 if in_external_macro(cx.sess(), impl_item.span) {
1415 let name = impl_item.ident.name.as_str();
1416 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
1417 let item = cx.tcx.hir().expect_item(parent);
1418 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1419 let self_ty = cx.tcx.type_of(def_id);
1421 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1422 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1423 if let hir::ItemKind::Impl{ of_trait: None, .. } = item.kind;
1425 let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
1426 let method_sig = cx.tcx.fn_sig(method_def_id);
1427 let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
1429 let first_arg_ty = &method_sig.inputs().iter().next();
1431 // check conventions w.r.t. conversion method names and predicates
1432 if let Some(first_arg_ty) = first_arg_ty;
1435 if cx.access_levels.is_exported(impl_item.hir_id) {
1436 // check missing trait implementations
1437 for &(method_name, n_args, fn_header, self_kind, out_type, trait_name) in &TRAIT_METHODS {
1438 if name == method_name &&
1439 sig.decl.inputs.len() == n_args &&
1440 out_type.matches(cx, &sig.decl.output) &&
1441 self_kind.matches(cx, self_ty, first_arg_ty) &&
1442 fn_header_equals(*fn_header, sig.header) {
1443 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, impl_item.span, &format!(
1444 "defining a method called `{}` on this type; consider implementing \
1445 the `{}` trait or choosing a less ambiguous name", name, trait_name));
1450 if let Some((ref conv, self_kinds)) = &CONVENTIONS
1452 .find(|(ref conv, _)| conv.check(&name))
1454 if !self_kinds.iter().any(|k| k.matches(cx, self_ty, first_arg_ty)) {
1455 let lint = if item.vis.node.is_pub() {
1456 WRONG_PUB_SELF_CONVENTION
1458 WRONG_SELF_CONVENTION
1465 &format!("methods called `{}` usually take {}; consider choosing a less ambiguous name",
1469 .map(|k| k.description())
1470 .collect::<Vec<_>>()
1479 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1480 let ret_ty = return_ty(cx, impl_item.hir_id);
1482 let contains_self_ty = |ty: Ty<'tcx>| {
1483 ty.walk().any(|inner| match inner.unpack() {
1484 GenericArgKind::Type(inner_ty) => same_tys(cx, self_ty, inner_ty),
1486 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => false,
1490 // walk the return type and check for Self (this does not check associated types)
1491 if contains_self_ty(ret_ty) {
1495 // if return type is impl trait, check the associated types
1496 if let ty::Opaque(def_id, _) = ret_ty.kind {
1497 // one of the associated types must be Self
1498 for predicate in cx.tcx.predicates_of(def_id).predicates {
1499 if let ty::PredicateKind::Projection(poly_projection_predicate) = predicate.0.kind() {
1500 let binder = poly_projection_predicate.ty();
1501 let associated_type = binder.skip_binder();
1503 // walk the associated type and check for Self
1504 if contains_self_ty(associated_type) {
1511 if name == "new" && !same_tys(cx, ret_ty, self_ty) {
1516 "methods called `new` usually return `Self`",
1523 /// Checks for the `OR_FUN_CALL` lint.
1524 #[allow(clippy::too_many_lines)]
1525 fn lint_or_fun_call<'a, 'tcx>(
1526 cx: &LateContext<'a, 'tcx>,
1527 expr: &hir::Expr<'_>,
1530 args: &'tcx [hir::Expr<'_>],
1532 // Searches an expression for method calls or function calls that aren't ctors
1533 struct FunCallFinder<'a, 'tcx> {
1534 cx: &'a LateContext<'a, 'tcx>,
1538 impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
1539 type Map = Map<'tcx>;
1541 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
1542 let call_found = match &expr.kind {
1543 // ignore enum and struct constructors
1544 hir::ExprKind::Call(..) => !is_ctor_or_promotable_const_function(self.cx, expr),
1545 hir::ExprKind::MethodCall(..) => true,
1554 intravisit::walk_expr(self, expr);
1558 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1559 intravisit::NestedVisitorMap::None
1563 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1564 fn check_unwrap_or_default(
1565 cx: &LateContext<'_, '_>,
1567 fun: &hir::Expr<'_>,
1568 self_expr: &hir::Expr<'_>,
1569 arg: &hir::Expr<'_>,
1575 if name == "unwrap_or";
1576 if let hir::ExprKind::Path(ref qpath) = fun.kind;
1577 let path = &*last_path_segment(qpath).ident.as_str();
1578 if ["default", "new"].contains(&path);
1579 let arg_ty = cx.tables.expr_ty(arg);
1580 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1581 if implements_trait(cx, arg_ty, default_trait_id, &[]);
1584 let mut applicability = Applicability::MachineApplicable;
1589 &format!("use of `{}` followed by a call to `{}`", name, path),
1592 "{}.unwrap_or_default()",
1593 snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
1605 /// Checks for `*or(foo())`.
1606 #[allow(clippy::too_many_arguments)]
1607 fn check_general_case<'a, 'tcx>(
1608 cx: &LateContext<'a, 'tcx>,
1612 self_expr: &hir::Expr<'_>,
1613 arg: &'tcx hir::Expr<'_>,
1617 // (path, fn_has_argument, methods, suffix)
1618 let know_types: &[(&[_], _, &[_], _)] = &[
1619 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1620 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1621 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1622 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1626 if know_types.iter().any(|k| k.2.contains(&name));
1628 let mut finder = FunCallFinder { cx: &cx, found: false };
1629 if { finder.visit_expr(&arg); finder.found };
1630 if !contains_return(&arg);
1632 let self_ty = cx.tables.expr_ty(self_expr);
1634 if let Some(&(_, fn_has_arguments, poss, suffix)) =
1635 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
1637 if poss.contains(&name);
1640 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1641 (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1642 (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1643 (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1645 let span_replace_word = method_span.with_hi(span.hi());
1650 &format!("use of `{}` followed by a function call", name),
1652 format!("{}_{}({})", name, suffix, sugg),
1653 Applicability::HasPlaceholders,
1659 if args.len() == 2 {
1660 match args[1].kind {
1661 hir::ExprKind::Call(ref fun, ref or_args) => {
1662 let or_has_args = !or_args.is_empty();
1663 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1676 hir::ExprKind::MethodCall(_, span, ref or_args) => check_general_case(
1683 !or_args.is_empty(),
1691 /// Checks for the `EXPECT_FUN_CALL` lint.
1692 #[allow(clippy::too_many_lines)]
1693 fn lint_expect_fun_call(
1694 cx: &LateContext<'_, '_>,
1695 expr: &hir::Expr<'_>,
1698 args: &[hir::Expr<'_>],
1700 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1702 fn get_arg_root<'a>(cx: &LateContext<'_, '_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1703 let mut arg_root = arg;
1705 arg_root = match &arg_root.kind {
1706 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1707 hir::ExprKind::MethodCall(method_name, _, call_args) => {
1708 if call_args.len() == 1
1709 && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1711 let arg_type = cx.tables.expr_ty(&call_args[0]);
1712 let base_type = walk_ptrs_ty(arg_type);
1713 base_type.kind == ty::Str || is_type_diagnostic_item(cx, base_type, sym!(string_type))
1727 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1728 // converted to string.
1729 fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1730 let arg_ty = cx.tables.expr_ty(arg);
1731 if is_type_diagnostic_item(cx, arg_ty, sym!(string_type)) {
1734 if let ty::Ref(_, ty, ..) = arg_ty.kind {
1735 if ty.kind == ty::Str && can_be_static_str(cx, arg) {
1742 // Check if an expression could have type `&'static str`, knowing that it
1743 // has type `&str` for some lifetime.
1744 fn can_be_static_str(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1746 hir::ExprKind::Lit(_) => true,
1747 hir::ExprKind::Call(fun, _) => {
1748 if let hir::ExprKind::Path(ref p) = fun.kind {
1749 match cx.tables.qpath_res(p, fun.hir_id) {
1750 hir::def::Res::Def(hir::def::DefKind::Fn, def_id)
1751 | hir::def::Res::Def(hir::def::DefKind::AssocFn, def_id) => matches!(
1752 cx.tcx.fn_sig(def_id).output().skip_binder().kind,
1753 ty::Ref(ty::ReStatic, ..)
1761 hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(arg.hir_id).map_or(false, |method_id| {
1763 cx.tcx.fn_sig(method_id).output().skip_binder().kind,
1764 ty::Ref(ty::ReStatic, ..)
1767 hir::ExprKind::Path(ref p) => match cx.tables.qpath_res(p, arg.hir_id) {
1768 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _) => true,
1775 fn generate_format_arg_snippet(
1776 cx: &LateContext<'_, '_>,
1778 applicability: &mut Applicability,
1781 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1782 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1783 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
1788 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1796 fn is_call(node: &hir::ExprKind<'_>) -> bool {
1798 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
1801 hir::ExprKind::Call(..)
1802 | hir::ExprKind::MethodCall(..)
1803 // These variants are debatable or require further examination
1804 | hir::ExprKind::Match(..)
1805 | hir::ExprKind::Block{ .. } => true,
1810 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
1814 let receiver_type = cx.tables.expr_ty_adjusted(&args[0]);
1815 let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym!(option_type)) {
1817 } else if is_type_diagnostic_item(cx, receiver_type, sym!(result_type)) {
1823 let arg_root = get_arg_root(cx, &args[1]);
1825 let span_replace_word = method_span.with_hi(expr.span.hi());
1827 let mut applicability = Applicability::MachineApplicable;
1829 //Special handling for `format!` as arg_root
1831 if let hir::ExprKind::Block(block, None) = &arg_root.kind;
1832 if block.stmts.len() == 1;
1833 if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
1834 if let Some(arg_root) = &local.init;
1835 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
1836 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
1837 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
1839 let fmt_spec = &format_args[0];
1840 let fmt_args = &format_args[1];
1842 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1844 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1846 let sugg = args.join(", ");
1852 &format!("use of `{}` followed by a function call", name),
1854 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1862 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1863 if requires_to_string(cx, arg_root) {
1864 arg_root_snippet.to_mut().push_str(".to_string()");
1871 &format!("use of `{}` followed by a function call", name),
1873 format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1878 /// Checks for the `CLONE_ON_COPY` lint.
1879 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
1880 let ty = cx.tables.expr_ty(expr);
1881 if let ty::Ref(_, inner, _) = arg_ty.kind {
1882 if let ty::Ref(_, innermost, _) = inner.kind {
1887 "using `clone` on a double-reference; \
1888 this will copy the reference instead of cloning the inner type",
1890 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1891 let mut ty = innermost;
1893 while let ty::Ref(_, inner, _) = ty.kind {
1897 let refs: String = iter::repeat('&').take(n + 1).collect();
1898 let derefs: String = iter::repeat('*').take(n).collect();
1899 let explicit = format!("<{}{}>::clone({})", refs, ty, snip);
1900 diag.span_suggestion(
1902 "try dereferencing it",
1903 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1904 Applicability::MaybeIncorrect,
1906 diag.span_suggestion(
1908 "or try being explicit if you are sure, that you want to clone a reference",
1910 Applicability::MaybeIncorrect,
1915 return; // don't report clone_on_copy
1919 if is_copy(cx, ty) {
1921 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1922 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
1923 match &cx.tcx.hir().get(parent) {
1924 hir::Node::Expr(parent) => match parent.kind {
1925 // &*x is a nop, &x.clone() is not
1926 hir::ExprKind::AddrOf(..) => return,
1927 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1928 hir::ExprKind::MethodCall(_, _, parent_args) if expr.hir_id == parent_args[0].hir_id => return,
1932 hir::Node::Stmt(stmt) => {
1933 if let hir::StmtKind::Local(ref loc) = stmt.kind {
1934 if let hir::PatKind::Ref(..) = loc.pat.kind {
1935 // let ref y = *x borrows x, let ref y = x.clone() does not
1943 // x.clone() might have dereferenced x, possibly through Deref impls
1944 if cx.tables.expr_ty(arg) == ty {
1945 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1947 let deref_count = cx
1949 .expr_adjustments(arg)
1952 if let ty::adjustment::Adjust::Deref(_) = adj.kind {
1959 let derefs: String = iter::repeat('*').take(deref_count).collect();
1960 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
1965 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |diag| {
1966 if let Some((text, snip)) = snip {
1967 diag.span_suggestion(expr.span, text, snip, Applicability::Unspecified);
1973 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
1974 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1976 if let ty::Adt(_, subst) = obj_ty.kind {
1977 let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) {
1979 } else if is_type_diagnostic_item(cx, obj_ty, sym::Arc) {
1981 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1991 "using `.clone()` on a ref-counted pointer",
1994 "{}::<{}>::clone(&{})",
1997 snippet(cx, arg.span, "_")
1999 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
2004 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2006 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
2007 let target = &arglists[0][0];
2008 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
2009 let ref_str = if self_ty.kind == ty::Str {
2011 } else if is_type_diagnostic_item(cx, self_ty, sym!(string_type)) {
2017 let mut applicability = Applicability::MachineApplicable;
2020 STRING_EXTEND_CHARS,
2022 "calling `.extend(_.chars())`",
2025 "{}.push_str({}{})",
2026 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
2028 snippet_with_applicability(cx, target.span, "_", &mut applicability)
2035 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2036 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
2037 if is_type_diagnostic_item(cx, obj_ty, sym!(string_type)) {
2038 lint_string_extend(cx, expr, args);
2042 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2044 let source_type = cx.tables.expr_ty(source);
2045 if let ty::Adt(def, substs) = source_type.kind;
2046 if cx.tcx.is_diagnostic_item(sym!(result_type), def.did);
2047 if match_type(cx, substs.type_at(0), &paths::CSTRING);
2051 TEMPORARY_CSTRING_AS_PTR,
2053 "you are getting the inner pointer of a temporary `CString`",
2055 diag.note("that pointer will be invalid outside this expression");
2056 diag.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2062 fn lint_iter_cloned_collect<'a, 'tcx>(
2063 cx: &LateContext<'a, 'tcx>,
2064 expr: &hir::Expr<'_>,
2065 iter_args: &'tcx [hir::Expr<'_>],
2068 if is_type_diagnostic_item(cx, cx.tables.expr_ty(expr), sym!(vec_type));
2069 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0]));
2070 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2075 ITER_CLONED_COLLECT,
2077 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2080 ".to_vec()".to_string(),
2081 Applicability::MachineApplicable,
2087 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2088 fn check_fold_with_op(
2089 cx: &LateContext<'_, '_>,
2090 expr: &hir::Expr<'_>,
2091 fold_args: &[hir::Expr<'_>],
2094 replacement_method_name: &str,
2095 replacement_has_args: bool,
2098 // Extract the body of the closure passed to fold
2099 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2100 let closure_body = cx.tcx.hir().body(body_id);
2101 let closure_expr = remove_blocks(&closure_body.value);
2103 // Check if the closure body is of the form `acc <op> some_expr(x)`
2104 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2105 if bin_op.node == op;
2107 // Extract the names of the two arguments to the closure
2108 if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2109 if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2111 if match_var(&*left_expr, first_arg_ident);
2112 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2115 let mut applicability = Applicability::MachineApplicable;
2116 let sugg = if replacement_has_args {
2118 "{replacement}(|{s}| {r})",
2119 replacement = replacement_method_name,
2120 s = second_arg_ident,
2121 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2126 replacement = replacement_method_name,
2133 fold_span.with_hi(expr.span.hi()),
2134 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2135 "this `.fold` can be written more succinctly using another method",
2144 // Check that this is a call to Iterator::fold rather than just some function called fold
2145 if !match_trait_method(cx, expr, &paths::ITERATOR) {
2150 fold_args.len() == 3,
2151 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2154 // Check if the first argument to .fold is a suitable literal
2155 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2157 ast::LitKind::Bool(false) => {
2158 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2160 ast::LitKind::Bool(true) => {
2161 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2163 ast::LitKind::Int(0, _) => {
2164 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2166 ast::LitKind::Int(1, _) => {
2167 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2174 fn lint_step_by<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2175 if match_trait_method(cx, expr, &paths::ITERATOR) {
2176 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
2179 ITERATOR_STEP_BY_ZERO,
2181 "Iterator::step_by(0) will panic at runtime",
2187 fn lint_iter_nth<'a, 'tcx>(
2188 cx: &LateContext<'a, 'tcx>,
2189 expr: &hir::Expr<'_>,
2190 nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2193 let iter_args = nth_and_iter_args[1];
2194 let mut_str = if is_mut { "_mut" } else { "" };
2195 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
2197 } else if is_type_diagnostic_item(cx, cx.tables.expr_ty(&iter_args[0]), sym!(vec_type)) {
2199 } else if is_type_diagnostic_item(cx, cx.tables.expr_ty(&iter_args[0]), sym!(vecdeque_type)) {
2202 let nth_args = nth_and_iter_args[0];
2203 lint_iter_nth_zero(cx, expr, &nth_args);
2204 return; // caller is not a type that we want to lint
2211 &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2213 &format!("calling `.get{}()` is both faster and more readable", mut_str),
2217 fn lint_iter_nth_zero<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2219 if match_trait_method(cx, expr, &paths::ITERATOR);
2220 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &nth_args[1]);
2222 let mut applicability = Applicability::MachineApplicable;
2227 "called `.nth(0)` on a `std::iter::Iterator`",
2229 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2236 fn lint_get_unwrap<'a, 'tcx>(
2237 cx: &LateContext<'a, 'tcx>,
2238 expr: &hir::Expr<'_>,
2239 get_args: &'tcx [hir::Expr<'_>],
2242 // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2243 // because they do not implement `IndexMut`
2244 let mut applicability = Applicability::MachineApplicable;
2245 let expr_ty = cx.tables.expr_ty(&get_args[0]);
2246 let get_args_str = if get_args.len() > 1 {
2247 snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
2249 return; // not linting on a .get().unwrap() chain or variant
2252 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2253 needs_ref = get_args_str.parse::<usize>().is_ok();
2255 } else if is_type_diagnostic_item(cx, expr_ty, sym!(vec_type)) {
2256 needs_ref = get_args_str.parse::<usize>().is_ok();
2258 } else if is_type_diagnostic_item(cx, expr_ty, sym!(vecdeque_type)) {
2259 needs_ref = get_args_str.parse::<usize>().is_ok();
2261 } else if !is_mut && is_type_diagnostic_item(cx, expr_ty, sym!(hashmap_type)) {
2264 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2268 return; // caller is not a type that we want to lint
2271 let mut span = expr.span;
2273 // Handle the case where the result is immediately dereferenced
2274 // by not requiring ref and pulling the dereference into the
2278 if let Some(parent) = get_parent_expr(cx, expr);
2279 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2286 let mut_str = if is_mut { "_mut" } else { "" };
2287 let borrow_str = if !needs_ref {
2300 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2301 mut_str, caller_type
2307 snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
2314 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
2315 // lint if caller of skip is an Iterator
2316 if match_trait_method(cx, expr, &paths::ITERATOR) {
2321 "called `skip(x).next()` on an iterator",
2323 "this is more succinctly expressed by calling `nth(x)`",
2328 fn derefs_to_slice<'a, 'tcx>(
2329 cx: &LateContext<'a, 'tcx>,
2330 expr: &'tcx hir::Expr<'tcx>,
2332 ) -> Option<&'tcx hir::Expr<'tcx>> {
2333 fn may_slice<'a>(cx: &LateContext<'_, 'a>, ty: Ty<'a>) -> bool {
2335 ty::Slice(_) => true,
2336 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2337 ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym!(vec_type)),
2338 ty::Array(_, size) => {
2339 if let Some(size) = size.try_eval_usize(cx.tcx, cx.param_env) {
2345 ty::Ref(_, inner, _) => may_slice(cx, inner),
2350 if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
2351 if path.ident.name == sym!(iter) && may_slice(cx, cx.tables.expr_ty(&args[0])) {
2358 ty::Slice(_) => Some(expr),
2359 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2360 ty::Ref(_, inner, _) => {
2361 if may_slice(cx, inner) {
2372 /// lint use of `unwrap()` for `Option`s and `Result`s
2373 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2374 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
2376 let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2377 Some((UNWRAP_USED, "an Option", "None"))
2378 } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2379 Some((UNWRAP_USED, "a Result", "Err"))
2384 if let Some((lint, kind, none_value)) = mess {
2389 &format!("used `unwrap()` on `{}` value", kind,),
2392 "if you don't want to handle the `{}` case gracefully, consider \
2393 using `expect()` to provide a better panic message",
2400 /// lint use of `expect()` for `Option`s and `Result`s
2401 fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2402 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&expect_args[0]));
2404 let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) {
2405 Some((EXPECT_USED, "an Option", "None"))
2406 } else if is_type_diagnostic_item(cx, obj_ty, sym!(result_type)) {
2407 Some((EXPECT_USED, "a Result", "Err"))
2412 if let Some((lint, kind, none_value)) = mess {
2417 &format!("used `expect()` on `{}` value", kind,),
2419 &format!("if this value is an `{}`, it will panic", none_value,),
2424 /// lint use of `ok().expect()` for `Result`s
2425 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2427 // lint if the caller of `ok()` is a `Result`
2428 if is_type_diagnostic_item(cx, cx.tables.expr_ty(&ok_args[0]), sym!(result_type));
2429 let result_type = cx.tables.expr_ty(&ok_args[0]);
2430 if let Some(error_type) = get_error_type(cx, result_type);
2431 if has_debug_impl(error_type, cx);
2438 "called `ok().expect()` on a `Result` value",
2440 "you can call `expect()` directly on the `Result`",
2446 /// lint use of `map().flatten()` for `Iterators` and 'Options'
2447 fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2448 // lint if caller of `.map().flatten()` is an Iterator
2449 if match_trait_method(cx, expr, &paths::ITERATOR) {
2450 let msg = "called `map(..).flatten()` on an `Iterator`. \
2451 This is more succinctly expressed by calling `.flat_map(..)`";
2452 let self_snippet = snippet(cx, map_args[0].span, "..");
2453 let func_snippet = snippet(cx, map_args[1].span, "..");
2454 let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
2460 "try using `flat_map` instead",
2462 Applicability::MachineApplicable,
2466 // lint if caller of `.map().flatten()` is an Option
2467 if is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_args[0]), sym!(option_type)) {
2468 let msg = "called `map(..).flatten()` on an `Option`. \
2469 This is more succinctly expressed by calling `.and_then(..)`";
2470 let self_snippet = snippet(cx, map_args[0].span, "..");
2471 let func_snippet = snippet(cx, map_args[1].span, "..");
2472 let hint = format!("{0}.and_then({1})", self_snippet, func_snippet);
2478 "try using `and_then` instead",
2480 Applicability::MachineApplicable,
2485 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2486 fn lint_map_unwrap_or_else<'a, 'tcx>(
2487 cx: &LateContext<'a, 'tcx>,
2488 expr: &'tcx hir::Expr<'_>,
2489 map_args: &'tcx [hir::Expr<'_>],
2490 unwrap_args: &'tcx [hir::Expr<'_>],
2492 // lint if the caller of `map()` is an `Option`
2493 let is_option = is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_args[0]), sym!(option_type));
2494 let is_result = is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_args[0]), sym!(result_type));
2496 if is_option || is_result {
2497 // Don't make a suggestion that may fail to compile due to mutably borrowing
2498 // the same variable twice.
2499 let map_mutated_vars = mutated_variables(&map_args[0], cx);
2500 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2501 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2502 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2510 let msg = if is_option {
2511 "called `map(f).unwrap_or_else(g)` on an `Option` value. This can be done more directly by calling \
2512 `map_or_else(g, f)` instead"
2514 "called `map(f).unwrap_or_else(g)` on a `Result` value. This can be done more directly by calling \
2515 `.map_or_else(g, f)` instead"
2517 // get snippets for args to map() and unwrap_or_else()
2518 let map_snippet = snippet(cx, map_args[1].span, "..");
2519 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2520 // lint, with note if neither arg is > 1 line and both map() and
2521 // unwrap_or_else() have the same span
2522 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2523 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2524 if same_span && !multiline {
2532 "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
2533 map_snippet, unwrap_snippet,
2536 } else if same_span && multiline {
2537 span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
2542 /// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
2543 fn lint_map_or_none<'a, 'tcx>(
2544 cx: &LateContext<'a, 'tcx>,
2545 expr: &'tcx hir::Expr<'_>,
2546 map_or_args: &'tcx [hir::Expr<'_>],
2548 let is_option = is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_or_args[0]), sym!(option_type));
2549 let is_result = is_type_diagnostic_item(cx, cx.tables.expr_ty(&map_or_args[0]), sym!(result_type));
2551 // There are two variants of this `map_or` lint:
2552 // (1) using `map_or` as an adapter from `Result<T,E>` to `Option<T>`
2553 // (2) using `map_or` as a combinator instead of `and_then`
2555 // (For this lint) we don't care if any other type calls `map_or`
2556 if !is_option && !is_result {
2560 let (lint_name, msg, instead, hint) = {
2561 let default_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2562 match_qpath(qpath, &paths::OPTION_NONE)
2567 if !default_arg_is_none {
2572 let f_arg_is_some = if let hir::ExprKind::Path(ref qpath) = map_or_args[2].kind {
2573 match_qpath(qpath, &paths::OPTION_SOME)
2579 let self_snippet = snippet(cx, map_or_args[0].span, "..");
2580 let func_snippet = snippet(cx, map_or_args[2].span, "..");
2581 let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \
2582 `and_then(f)` instead";
2586 "try using `and_then` instead",
2587 format!("{0}.and_then({1})", self_snippet, func_snippet),
2589 } else if f_arg_is_some {
2590 let msg = "called `map_or(None, Some)` on a `Result` value. This can be done more directly by calling \
2592 let self_snippet = snippet(cx, map_or_args[0].span, "..");
2594 RESULT_MAP_OR_INTO_OPTION,
2596 "try using `ok` instead",
2597 format!("{0}.ok()", self_snippet),
2612 Applicability::MachineApplicable,
2616 /// lint use of `filter().next()` for `Iterators`
2617 fn lint_filter_next<'a, 'tcx>(
2618 cx: &LateContext<'a, 'tcx>,
2619 expr: &'tcx hir::Expr<'_>,
2620 filter_args: &'tcx [hir::Expr<'_>],
2622 // lint if caller of `.filter().next()` is an Iterator
2623 if match_trait_method(cx, expr, &paths::ITERATOR) {
2624 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2625 `.find(p)` instead.";
2626 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2627 if filter_snippet.lines().count() <= 1 {
2628 // add note if not multi-line
2635 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2638 span_lint(cx, FILTER_NEXT, expr.span, msg);
2643 /// lint use of `skip_while().next()` for `Iterators`
2644 fn lint_skip_while_next<'a, 'tcx>(
2645 cx: &LateContext<'a, 'tcx>,
2646 expr: &'tcx hir::Expr<'_>,
2647 _skip_while_args: &'tcx [hir::Expr<'_>],
2649 // lint if caller of `.skip_while().next()` is an Iterator
2650 if match_trait_method(cx, expr, &paths::ITERATOR) {
2655 "called `skip_while(p).next()` on an `Iterator`",
2657 "this is more succinctly expressed by calling `.find(!p)` instead",
2662 /// lint use of `filter().map()` for `Iterators`
2663 fn lint_filter_map<'a, 'tcx>(
2664 cx: &LateContext<'a, 'tcx>,
2665 expr: &'tcx hir::Expr<'_>,
2666 _filter_args: &'tcx [hir::Expr<'_>],
2667 _map_args: &'tcx [hir::Expr<'_>],
2669 // lint if caller of `.filter().map()` is an Iterator
2670 if match_trait_method(cx, expr, &paths::ITERATOR) {
2671 let msg = "called `filter(p).map(q)` on an `Iterator`";
2672 let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2673 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2677 /// lint use of `filter_map().next()` for `Iterators`
2678 fn lint_filter_map_next<'a, 'tcx>(
2679 cx: &LateContext<'a, 'tcx>,
2680 expr: &'tcx hir::Expr<'_>,
2681 filter_args: &'tcx [hir::Expr<'_>],
2683 if match_trait_method(cx, expr, &paths::ITERATOR) {
2684 let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2685 `.find_map(p)` instead.";
2686 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2687 if filter_snippet.lines().count() <= 1 {
2694 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2697 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2702 /// lint use of `find().map()` for `Iterators`
2703 fn lint_find_map<'a, 'tcx>(
2704 cx: &LateContext<'a, 'tcx>,
2705 expr: &'tcx hir::Expr<'_>,
2706 _find_args: &'tcx [hir::Expr<'_>],
2707 map_args: &'tcx [hir::Expr<'_>],
2709 // lint if caller of `.filter().map()` is an Iterator
2710 if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2711 let msg = "called `find(p).map(q)` on an `Iterator`";
2712 let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2713 span_lint_and_help(cx, FIND_MAP, expr.span, msg, None, hint);
2717 /// lint use of `filter_map().map()` for `Iterators`
2718 fn lint_filter_map_map<'a, 'tcx>(
2719 cx: &LateContext<'a, 'tcx>,
2720 expr: &'tcx hir::Expr<'_>,
2721 _filter_args: &'tcx [hir::Expr<'_>],
2722 _map_args: &'tcx [hir::Expr<'_>],
2724 // lint if caller of `.filter().map()` is an Iterator
2725 if match_trait_method(cx, expr, &paths::ITERATOR) {
2726 let msg = "called `filter_map(p).map(q)` on an `Iterator`";
2727 let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2728 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2732 /// lint use of `filter().flat_map()` for `Iterators`
2733 fn lint_filter_flat_map<'a, 'tcx>(
2734 cx: &LateContext<'a, 'tcx>,
2735 expr: &'tcx hir::Expr<'_>,
2736 _filter_args: &'tcx [hir::Expr<'_>],
2737 _map_args: &'tcx [hir::Expr<'_>],
2739 // lint if caller of `.filter().flat_map()` is an Iterator
2740 if match_trait_method(cx, expr, &paths::ITERATOR) {
2741 let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
2742 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2743 and filtering by returning `iter::empty()`";
2744 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2748 /// lint use of `filter_map().flat_map()` for `Iterators`
2749 fn lint_filter_map_flat_map<'a, 'tcx>(
2750 cx: &LateContext<'a, 'tcx>,
2751 expr: &'tcx hir::Expr<'_>,
2752 _filter_args: &'tcx [hir::Expr<'_>],
2753 _map_args: &'tcx [hir::Expr<'_>],
2755 // lint if caller of `.filter_map().flat_map()` is an Iterator
2756 if match_trait_method(cx, expr, &paths::ITERATOR) {
2757 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
2758 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2759 and filtering by returning `iter::empty()`";
2760 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, None, hint);
2764 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2765 fn lint_flat_map_identity<'a, 'tcx>(
2766 cx: &LateContext<'a, 'tcx>,
2767 expr: &'tcx hir::Expr<'_>,
2768 flat_map_args: &'tcx [hir::Expr<'_>],
2769 flat_map_span: Span,
2771 if match_trait_method(cx, expr, &paths::ITERATOR) {
2772 let arg_node = &flat_map_args[1].kind;
2774 let apply_lint = |message: &str| {
2778 flat_map_span.with_hi(expr.span.hi()),
2781 "flatten()".to_string(),
2782 Applicability::MachineApplicable,
2787 if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
2788 let body = cx.tcx.hir().body(*body_id);
2790 if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
2791 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
2793 if path.segments.len() == 1;
2794 if path.segments[0].ident.as_str() == binding_ident.as_str();
2797 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
2802 if let hir::ExprKind::Path(ref qpath) = arg_node;
2804 if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2807 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
2813 /// lint searching an Iterator followed by `is_some()`
2814 fn lint_search_is_some<'a, 'tcx>(
2815 cx: &LateContext<'a, 'tcx>,
2816 expr: &'tcx hir::Expr<'_>,
2817 search_method: &str,
2818 search_args: &'tcx [hir::Expr<'_>],
2819 is_some_args: &'tcx [hir::Expr<'_>],
2822 // lint if caller of search is an Iterator
2823 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2825 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2826 expressed by calling `any()`.",
2829 let search_snippet = snippet(cx, search_args[1].span, "..");
2830 if search_snippet.lines().count() <= 1 {
2831 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2832 // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
2833 let any_search_snippet = if_chain! {
2834 if search_method == "find";
2835 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
2836 let closure_body = cx.tcx.hir().body(body_id);
2837 if let Some(closure_arg) = closure_body.params.get(0);
2839 if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
2840 Some(search_snippet.replacen('&', "", 1))
2841 } else if let Some(name) = get_arg_name(&closure_arg.pat) {
2842 Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
2850 // add note if not multi-line
2854 method_span.with_hi(expr.span.hi()),
2859 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2861 Applicability::MachineApplicable,
2864 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2869 /// Used for `lint_binary_expr_with_method_call`.
2870 #[derive(Copy, Clone)]
2871 struct BinaryExprInfo<'a> {
2872 expr: &'a hir::Expr<'a>,
2873 chain: &'a hir::Expr<'a>,
2874 other: &'a hir::Expr<'a>,
2878 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2879 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
2880 macro_rules! lint_with_both_lhs_and_rhs {
2881 ($func:ident, $cx:expr, $info:ident) => {
2882 if !$func($cx, $info) {
2883 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2884 if $func($cx, $info) {
2891 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2892 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2893 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2894 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2897 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2899 cx: &LateContext<'_, '_>,
2900 info: &BinaryExprInfo<'_>,
2901 chain_methods: &[&str],
2902 lint: &'static Lint,
2906 if let Some(args) = method_chain_args(info.chain, chain_methods);
2907 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2908 if arg_char.len() == 1;
2909 if let hir::ExprKind::Path(ref qpath) = fun.kind;
2910 if let Some(segment) = single_segment_path(qpath);
2911 if segment.ident.name == sym!(Some);
2913 let mut applicability = Applicability::MachineApplicable;
2914 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
2916 if self_ty.kind != ty::Str {
2924 &format!("you should use the `{}` method", suggest),
2926 format!("{}{}.{}({})",
2927 if info.eq { "" } else { "!" },
2928 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2930 snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
2941 /// Checks for the `CHARS_NEXT_CMP` lint.
2942 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2943 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2946 /// Checks for the `CHARS_LAST_CMP` lint.
2947 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2948 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2951 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2955 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2956 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
2957 cx: &LateContext<'a, 'tcx>,
2958 info: &BinaryExprInfo<'_>,
2959 chain_methods: &[&str],
2960 lint: &'static Lint,
2964 if let Some(args) = method_chain_args(info.chain, chain_methods);
2965 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2966 if let ast::LitKind::Char(c) = lit.node;
2968 let mut applicability = Applicability::MachineApplicable;
2973 &format!("you should use the `{}` method", suggest),
2975 format!("{}{}.{}('{}')",
2976 if info.eq { "" } else { "!" },
2977 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2990 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2991 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2992 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2995 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
2996 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2997 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3000 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3004 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3005 fn lint_single_char_pattern<'a, 'tcx>(
3006 cx: &LateContext<'a, 'tcx>,
3007 _expr: &'tcx hir::Expr<'_>,
3008 arg: &'tcx hir::Expr<'_>,
3011 if let hir::ExprKind::Lit(lit) = &arg.kind;
3012 if let ast::LitKind::Str(r, style) = lit.node;
3013 if r.as_str().len() == 1;
3015 let mut applicability = Applicability::MachineApplicable;
3016 let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
3017 let ch = if let ast::StrStyle::Raw(nhash) = style {
3018 let nhash = nhash as usize;
3019 // for raw string: r##"a"##
3020 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3022 // for regular string: "a"
3023 &snip[1..(snip.len() - 1)]
3025 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3028 SINGLE_CHAR_PATTERN,
3030 "single-character string constant used as pattern",
3031 "try using a `char` instead",
3039 /// Checks for the `USELESS_ASREF` lint.
3040 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3041 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3042 // check if the call is to the actual `AsRef` or `AsMut` trait
3043 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3044 // check if the type after `as_ref` or `as_mut` is the same as before
3045 let recvr = &as_ref_args[0];
3046 let rcv_ty = cx.tables.expr_ty(recvr);
3047 let res_ty = cx.tables.expr_ty(expr);
3048 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3049 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3050 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3051 // allow the `as_ref` or `as_mut` if it is followed by another method call
3053 if let Some(parent) = get_parent_expr(cx, expr);
3054 if let hir::ExprKind::MethodCall(_, ref span, _) = parent.kind;
3055 if span != &expr.span;
3061 let mut applicability = Applicability::MachineApplicable;
3066 &format!("this call to `{}` does nothing", call_name),
3068 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
3075 fn ty_has_iter_method(cx: &LateContext<'_, '_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3076 has_iter_method(cx, self_ref_ty).map(|ty_name| {
3077 let mutbl = match self_ref_ty.kind {
3078 ty::Ref(_, _, mutbl) => mutbl,
3079 _ => unreachable!(),
3081 let method_name = match mutbl {
3082 hir::Mutability::Not => "iter",
3083 hir::Mutability::Mut => "iter_mut",
3085 (ty_name, method_name)
3089 fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3090 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3093 if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3099 "this `.into_iter()` call is equivalent to `.{}()` and will not move the `{}`",
3103 method_name.to_string(),
3104 Applicability::MachineApplicable,
3109 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3110 fn lint_maybe_uninit(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3112 if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3114 if let hir::ExprKind::Path(ref path) = callee.kind;
3115 if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3116 if !is_maybe_uninit_ty_valid(cx, cx.tables.expr_ty_adjusted(outer));
3120 UNINIT_ASSUMED_INIT,
3122 "this call for this type may be undefined behavior"
3128 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
3130 ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3131 ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3132 ty::Adt(ref adt, _) => match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT),
3137 fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
3142 "this call to `map()` won't have an effect on the call to `count()`",
3144 "make sure you did not confuse `map` with `filter` or `for_each`",
3148 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3149 fn lint_option_as_ref_deref<'a, 'tcx>(
3150 cx: &LateContext<'a, 'tcx>,
3151 expr: &hir::Expr<'_>,
3152 as_ref_args: &[hir::Expr<'_>],
3153 map_args: &[hir::Expr<'_>],
3156 let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not);
3158 let option_ty = cx.tables.expr_ty(&as_ref_args[0]);
3159 if !is_type_diagnostic_item(cx, option_ty, sym!(option_type)) {
3163 let deref_aliases: [&[&str]; 9] = [
3164 &paths::DEREF_TRAIT_METHOD,
3165 &paths::DEREF_MUT_TRAIT_METHOD,
3166 &paths::CSTRING_AS_C_STR,
3167 &paths::OS_STRING_AS_OS_STR,
3168 &paths::PATH_BUF_AS_PATH,
3169 &paths::STRING_AS_STR,
3170 &paths::STRING_AS_MUT_STR,
3171 &paths::VEC_AS_SLICE,
3172 &paths::VEC_AS_MUT_SLICE,
3175 let is_deref = match map_args[1].kind {
3176 hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3177 hir::ExprKind::Closure(_, _, body_id, _, _) => {
3178 let closure_body = cx.tcx.hir().body(body_id);
3179 let closure_expr = remove_blocks(&closure_body.value);
3181 match &closure_expr.kind {
3182 hir::ExprKind::MethodCall(_, _, args) => {
3185 if let hir::ExprKind::Path(qpath) = &args[0].kind;
3186 if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id);
3187 if closure_body.params[0].pat.hir_id == local_id;
3188 let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::<Box<[_]>>();
3189 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3191 let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap();
3192 deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3198 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref inner) if same_mutability(m) => {
3200 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind;
3201 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind;
3202 if let hir::ExprKind::Path(ref qpath) = inner2.kind;
3203 if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, inner2.hir_id);
3205 closure_body.params[0].pat.hir_id == local_id
3218 let current_method = if is_mut {
3219 format!(".as_mut().map({})", snippet(cx, map_args[1].span, ".."))
3221 format!(".as_ref().map({})", snippet(cx, map_args[1].span, ".."))
3223 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3224 let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3225 let suggestion = format!("try using {} instead", method_hint);
3228 "called `{0}` on an Option value. This can be done more directly \
3229 by calling `{1}` instead",
3230 current_method, hint
3234 OPTION_AS_REF_DEREF,
3239 Applicability::MachineApplicable,
3244 /// Given a `Result<T, E>` type, return its error type (`E`).
3245 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3247 ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym!(result_type)) => substs.types().nth(1),
3252 /// This checks whether a given type is known to implement Debug.
3253 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
3255 .get_diagnostic_item(sym::debug_trait)
3256 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3261 StartsWith(&'static str),
3265 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3266 (Convention::Eq("new"), &[SelfKind::No]),
3267 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3268 (Convention::StartsWith("from_"), &[SelfKind::No]),
3269 (Convention::StartsWith("into_"), &[SelfKind::Value]),
3270 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3271 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3272 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3275 const FN_HEADER: hir::FnHeader = hir::FnHeader {
3276 unsafety: hir::Unsafety::Normal,
3277 constness: hir::Constness::NotConst,
3278 asyncness: hir::IsAsync::NotAsync,
3279 abi: rustc_target::spec::abi::Abi::Rust,
3283 const TRAIT_METHODS: [(&str, usize, &hir::FnHeader, SelfKind, OutType, &str); 30] = [
3284 ("add", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Add"),
3285 ("as_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
3286 ("as_ref", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
3287 ("bitand", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
3288 ("bitor", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
3289 ("bitxor", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
3290 ("borrow", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
3291 ("borrow_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
3292 ("clone", 1, &FN_HEADER, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
3293 ("cmp", 2, &FN_HEADER, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
3294 ("default", 0, &FN_HEADER, SelfKind::No, OutType::Any, "std::default::Default"),
3295 ("deref", 1, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
3296 ("deref_mut", 1, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
3297 ("div", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Div"),
3298 ("drop", 1, &FN_HEADER, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
3299 ("eq", 2, &FN_HEADER, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
3300 ("from_iter", 1, &FN_HEADER, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
3301 ("from_str", 1, &FN_HEADER, SelfKind::No, OutType::Any, "std::str::FromStr"),
3302 ("hash", 2, &FN_HEADER, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
3303 ("index", 2, &FN_HEADER, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
3304 ("index_mut", 2, &FN_HEADER, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
3305 ("into_iter", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
3306 ("mul", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Mul"),
3307 ("neg", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Neg"),
3308 ("next", 1, &FN_HEADER, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
3309 ("not", 1, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Not"),
3310 ("rem", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Rem"),
3311 ("shl", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Shl"),
3312 ("shr", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Shr"),
3313 ("sub", 2, &FN_HEADER, SelfKind::Value, OutType::Any, "std::ops::Sub"),
3317 const PATTERN_METHODS: [(&str, usize); 17] = [
3325 ("split_terminator", 1),
3326 ("rsplit_terminator", 1),
3331 ("match_indices", 1),
3332 ("rmatch_indices", 1),
3333 ("trim_start_matches", 1),
3334 ("trim_end_matches", 1),
3337 #[derive(Clone, Copy, PartialEq, Debug)]
3346 fn matches<'a>(self, cx: &LateContext<'_, 'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3347 fn matches_value<'a>(cx: &LateContext<'_, 'a>, parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3348 if ty == parent_ty {
3350 } else if ty.is_box() {
3351 ty.boxed_ty() == parent_ty
3352 } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) {
3353 if let ty::Adt(_, substs) = ty.kind {
3354 substs.types().next().map_or(false, |t| t == parent_ty)
3364 cx: &LateContext<'_, 'a>,
3365 mutability: hir::Mutability,
3369 if let ty::Ref(_, t, m) = ty.kind {
3370 return m == mutability && t == parent_ty;
3373 let trait_path = match mutability {
3374 hir::Mutability::Not => &paths::ASREF_TRAIT,
3375 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3378 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3380 None => return false,
3382 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3386 Self::Value => matches_value(cx, parent_ty, ty),
3387 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3388 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3389 Self::No => ty != parent_ty,
3394 fn description(self) -> &'static str {
3396 Self::Value => "self by value",
3397 Self::Ref => "self by reference",
3398 Self::RefMut => "self by mutable reference",
3399 Self::No => "no self",
3406 fn check(&self, other: &str) -> bool {
3408 Self::Eq(this) => this == other,
3409 Self::StartsWith(this) => other.starts_with(this) && this != other,
3414 impl fmt::Display for Convention {
3415 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3417 Self::Eq(this) => this.fmt(f),
3418 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3423 #[derive(Clone, Copy)]
3432 fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FnRetTy<'_>) -> bool {
3433 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3435 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3436 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3437 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3438 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3439 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3445 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3446 if let hir::TyKind::Path(ref p) = ty.kind {
3447 match_qpath(p, &["bool"])
3453 // Returns `true` if `expr` contains a return expression
3454 fn contains_return(expr: &hir::Expr<'_>) -> bool {
3455 struct RetCallFinder {
3459 impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
3460 type Map = Map<'tcx>;
3462 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
3466 if let hir::ExprKind::Ret(..) = &expr.kind {
3469 intravisit::walk_expr(self, expr);
3473 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
3474 intravisit::NestedVisitorMap::None
3478 let mut visitor = RetCallFinder { found: false };
3479 visitor.visit_expr(expr);
3483 fn check_pointer_offset(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3486 if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.tables.expr_ty(&args[0]).kind;
3487 if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3490 span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3495 fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3496 let ty = cx.tables.expr_ty(&args[0]);
3498 if !match_type(cx, ty, &paths::FILE_TYPE) {
3504 let lint_unary: &str;
3505 let help_unary: &str;
3507 if let Some(parent) = get_parent_expr(cx, expr);
3508 if let hir::ExprKind::Unary(op, _) = parent.kind;
3509 if op == hir::UnOp::UnNot;
3522 let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3523 let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3524 span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, None, &help_msg);
3527 fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
3528 expected.constness == actual.constness
3529 && expected.unsafety == actual.unsafety
3530 && expected.asyncness == actual.asyncness