1 mod inefficient_to_string;
2 mod manual_saturating_arithmetic;
3 mod option_map_unwrap_or;
4 mod unnecessary_filter_map;
10 use if_chain::if_chain;
12 use rustc_errors::Applicability;
14 use rustc_hir::intravisit::{self, Visitor};
15 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::lint::in_external_macro;
18 use rustc_middle::ty::{self, Predicate, Ty};
19 use rustc_session::{declare_lint_pass, declare_tool_lint};
20 use rustc_span::source_map::Span;
21 use rustc_span::symbol::{sym, Symbol, SymbolStr};
23 use crate::consts::{constant, Constant};
24 use crate::utils::usage::mutated_variables;
26 get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, implements_trait, in_macro, is_copy,
27 is_ctor_or_promotable_const_function, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
28 match_def_path, match_qpath, match_trait_method, match_type, match_var, method_calls, method_chain_args, paths,
29 remove_blocks, return_ty, same_tys, single_segment_path, snippet, snippet_with_applicability,
30 snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
31 span_lint_and_then, sugg, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
34 declare_clippy_lint! {
35 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
37 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
38 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
39 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
40 /// `Allow` by default.
42 /// **Known problems:** None.
46 /// Using unwrap on an `Option`:
49 /// let opt = Some(1);
56 /// let opt = Some(1);
57 /// opt.expect("more helpful message");
59 pub OPTION_UNWRAP_USED,
61 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
64 declare_clippy_lint! {
65 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
67 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
68 /// values. Normally, you want to implement more sophisticated error handling,
69 /// and propagate errors upwards with `?` operator.
71 /// Even if you want to panic on errors, not all `Error`s implement good
72 /// messages on display. Therefore, it may be beneficial to look at the places
73 /// where they may get displayed. Activate this lint to do just that.
75 /// **Known problems:** None.
78 /// Using unwrap on an `Result`:
81 /// let res: Result<usize, ()> = Ok(1);
88 /// let res: Result<usize, ()> = Ok(1);
89 /// res.expect("more helpful message");
91 pub RESULT_UNWRAP_USED,
93 "using `Result.unwrap()`, which might be better handled"
96 declare_clippy_lint! {
97 /// **What it does:** Checks for `.expect()` calls on `Option`s.
99 /// **Why is this bad?** Usually it is better to handle the `None` case. Still,
100 /// for a lot of quick-and-dirty code, `expect` is a good choice, which is why
101 /// this lint is `Allow` by default.
103 /// **Known problems:** None.
107 /// Using expect on an `Option`:
110 /// let opt = Some(1);
111 /// opt.expect("one");
117 /// let opt = Some(1);
120 pub OPTION_EXPECT_USED,
122 "using `Option.expect()`, which might be better handled"
125 declare_clippy_lint! {
126 /// **What it does:** Checks for `.expect()` calls on `Result`s.
128 /// **Why is this bad?** `result.expect()` will let the thread panic on `Err`
129 /// values. Normally, you want to implement more sophisticated error handling,
130 /// and propagate errors upwards with `?` operator.
132 /// **Known problems:** None.
135 /// Using expect on an `Result`:
138 /// let res: Result<usize, ()> = Ok(1);
139 /// res.expect("one");
145 /// let res: Result<usize, ()> = Ok(1);
147 /// # Ok::<(), ()>(())
149 pub RESULT_EXPECT_USED,
151 "using `Result.expect()`, which might be better handled"
154 declare_clippy_lint! {
155 /// **What it does:** Checks for methods that should live in a trait
156 /// implementation of a `std` trait (see [llogiq's blog
157 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
158 /// information) instead of an inherent implementation.
160 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
161 /// the code, often with very little cost. Also people seeing a `mul(...)`
163 /// may expect `*` to work equally, so you should have good reason to disappoint
166 /// **Known problems:** None.
172 /// fn add(&self, other: &X) -> X {
178 pub SHOULD_IMPLEMENT_TRAIT,
180 "defining a method that should be implementing a std trait"
183 declare_clippy_lint! {
184 /// **What it does:** Checks for methods with certain name prefixes and which
185 /// doesn't match how self is taken. The actual rules are:
187 /// |Prefix |`self` taken |
188 /// |-------|----------------------|
189 /// |`as_` |`&self` or `&mut self`|
191 /// |`into_`|`self` |
192 /// |`is_` |`&self` or none |
193 /// |`to_` |`&self` |
195 /// **Why is this bad?** Consistency breeds readability. If you follow the
196 /// conventions, your users won't be surprised that they, e.g., need to supply a
197 /// mutable reference to a `as_..` function.
199 /// **Known problems:** None.
205 /// fn as_str(self) -> &'static str {
211 pub WRONG_SELF_CONVENTION,
213 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
216 declare_clippy_lint! {
217 /// **What it does:** This is the same as
218 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
220 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
222 /// **Known problems:** Actually *renaming* the function may break clients if
223 /// the function is part of the public interface. In that case, be mindful of
224 /// the stability guarantees you've given your users.
230 /// pub fn as_str(self) -> &'a str {
235 pub WRONG_PUB_SELF_CONVENTION,
237 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
240 declare_clippy_lint! {
241 /// **What it does:** Checks for usage of `ok().expect(..)`.
243 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
244 /// directly to get a better error message.
246 /// **Known problems:** The error type needs to implement `Debug`
250 /// # let x = Ok::<_, ()>(());
251 /// x.ok().expect("why did I do this again?")
255 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
258 declare_clippy_lint! {
259 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
261 /// **Why is this bad?** Readability, this can be written more concisely as
262 /// `_.map_or(_, _)`.
264 /// **Known problems:** The order of the arguments is not in execution order
268 /// # let x = Some(1);
269 /// x.map(|a| a + 1).unwrap_or(0);
271 pub OPTION_MAP_UNWRAP_OR,
273 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as `map_or(a, f)`"
276 declare_clippy_lint! {
277 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
279 /// **Why is this bad?** Readability, this can be written more concisely as
280 /// `_.map_or_else(_, _)`.
282 /// **Known problems:** The order of the arguments is not in execution order.
286 /// # let x = Some(1);
287 /// # fn some_function() -> usize { 1 }
288 /// x.map(|a| a + 1).unwrap_or_else(some_function);
290 pub OPTION_MAP_UNWRAP_OR_ELSE,
292 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `map_or_else(g, f)`"
295 declare_clippy_lint! {
296 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
298 /// **Why is this bad?** Readability, this can be written more concisely as
299 /// `result.map_or_else(_, _)`.
301 /// **Known problems:** None.
305 /// # let x: Result<usize, ()> = Ok(1);
306 /// # fn some_function(foo: ()) -> usize { 1 }
307 /// x.map(|a| a + 1).unwrap_or_else(some_function);
309 pub RESULT_MAP_UNWRAP_OR_ELSE,
311 "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `.map_or_else(g, f)`"
314 declare_clippy_lint! {
315 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
317 /// **Why is this bad?** Readability, this can be written more concisely as
320 /// **Known problems:** The order of the arguments is not in execution order.
324 /// # let opt = Some(1);
325 /// opt.map_or(None, |a| Some(a + 1))
328 pub OPTION_MAP_OR_NONE,
330 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
333 declare_clippy_lint! {
334 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`.
336 /// **Why is this bad?** Readability, this can be written more concisely as
339 /// **Known problems:** None
344 /// let x = Some("foo");
345 /// let _ = x.and_then(|s| Some(s.len()));
348 /// The correct use would be:
351 /// let x = Some("foo");
352 /// let _ = x.map(|s| s.len());
354 pub OPTION_AND_THEN_SOME,
356 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
359 declare_clippy_lint! {
360 /// **What it does:** Checks for usage of `_.filter(_).next()`.
362 /// **Why is this bad?** Readability, this can be written more concisely as
365 /// **Known problems:** None.
369 /// # let vec = vec![1];
370 /// vec.iter().filter(|x| **x == 0).next();
372 /// Could be written as
374 /// # let vec = vec![1];
375 /// vec.iter().find(|x| **x == 0);
379 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
382 declare_clippy_lint! {
383 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
385 /// **Why is this bad?** Readability, this can be written more concisely as
386 /// `_.find(!condition)`.
388 /// **Known problems:** None.
392 /// # let vec = vec![1];
393 /// vec.iter().skip_while(|x| **x == 0).next();
395 /// Could be written as
397 /// # let vec = vec![1];
398 /// vec.iter().find(|x| **x != 0);
402 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
405 declare_clippy_lint! {
406 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
408 /// **Why is this bad?** Readability, this can be written more concisely as a
409 /// single method call.
411 /// **Known problems:**
415 /// let vec = vec![vec![1]];
416 /// vec.iter().map(|x| x.iter()).flatten();
420 "using combinations of `flatten` and `map` which can usually be written as a single method call"
423 declare_clippy_lint! {
424 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
425 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
427 /// **Why is this bad?** Readability, this can be written more concisely as a
428 /// single method call.
430 /// **Known problems:** Often requires a condition + Option/Iterator creation
431 /// inside the closure.
435 /// let vec = vec![1];
436 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
440 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
443 declare_clippy_lint! {
444 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
446 /// **Why is this bad?** Readability, this can be written more concisely as a
447 /// single method call.
449 /// **Known problems:** None
453 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
455 /// Can be written as
458 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
462 "using combination of `filter_map` and `next` which can usually be written as a single method call"
465 declare_clippy_lint! {
466 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
468 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
470 /// **Known problems:** None
474 /// # let iter = vec![vec![0]].into_iter();
475 /// iter.flat_map(|x| x);
477 /// Can be written as
479 /// # let iter = vec![vec![0]].into_iter();
482 pub FLAT_MAP_IDENTITY,
484 "call to `flat_map` where `flatten` is sufficient"
487 declare_clippy_lint! {
488 /// **What it does:** Checks for usage of `_.find(_).map(_)`.
490 /// **Why is this bad?** Readability, this can be written more concisely as a
491 /// single method call.
493 /// **Known problems:** Often requires a condition + Option/Iterator creation
494 /// inside the closure.
498 /// (0..3).find(|x| *x == 2).map(|x| x * 2);
500 /// Can be written as
502 /// (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
506 "using a combination of `find` and `map` can usually be written as a single method call"
509 declare_clippy_lint! {
510 /// **What it does:** Checks for an iterator search (such as `find()`,
511 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
513 /// **Why is this bad?** Readability, this can be written more concisely as
516 /// **Known problems:** None.
520 /// # let vec = vec![1];
521 /// vec.iter().find(|x| **x == 0).is_some();
523 /// Could be written as
525 /// # let vec = vec![1];
526 /// vec.iter().any(|x| *x == 0);
530 "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
533 declare_clippy_lint! {
534 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
535 /// if it starts with a given char.
537 /// **Why is this bad?** Readability, this can be written more concisely as
538 /// `_.starts_with(_)`.
540 /// **Known problems:** None.
544 /// let name = "foo";
545 /// if name.chars().next() == Some('_') {};
547 /// Could be written as
549 /// let name = "foo";
550 /// if name.starts_with('_') {};
554 "using `.chars().next()` to check if a string starts with a char"
557 declare_clippy_lint! {
558 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
559 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
560 /// `unwrap_or_default` instead.
562 /// **Why is this bad?** The function will always be called and potentially
563 /// allocate an object acting as the default.
565 /// **Known problems:** If the function has side-effects, not calling it will
566 /// change the semantic of the program, but you shouldn't rely on that anyway.
570 /// # let foo = Some(String::new());
571 /// foo.unwrap_or(String::new());
573 /// this can instead be written:
575 /// # let foo = Some(String::new());
576 /// foo.unwrap_or_else(String::new);
580 /// # let foo = Some(String::new());
581 /// foo.unwrap_or_default();
585 "using any `*or` method with a function call, which suggests `*or_else`"
588 declare_clippy_lint! {
589 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
590 /// etc., and suggests to use `unwrap_or_else` instead
592 /// **Why is this bad?** The function will always be called.
594 /// **Known problems:** If the function has side-effects, not calling it will
595 /// change the semantics of the program, but you shouldn't rely on that anyway.
599 /// # let foo = Some(String::new());
600 /// # let err_code = "418";
601 /// # let err_msg = "I'm a teapot";
602 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
606 /// # let foo = Some(String::new());
607 /// # let err_code = "418";
608 /// # let err_msg = "I'm a teapot";
609 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
611 /// this can instead be written:
613 /// # let foo = Some(String::new());
614 /// # let err_code = "418";
615 /// # let err_msg = "I'm a teapot";
616 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
620 "using any `expect` method with a function call"
623 declare_clippy_lint! {
624 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
626 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
627 /// generics, not for using the `clone` method on a concrete type.
629 /// **Known problems:** None.
637 "using `clone` on a `Copy` type"
640 declare_clippy_lint! {
641 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
642 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
643 /// function syntax instead (e.g., `Rc::clone(foo)`).
645 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
646 /// can obscure the fact that only the pointer is being cloned, not the underlying
651 /// # use std::rc::Rc;
652 /// let x = Rc::new(1);
655 pub CLONE_ON_REF_PTR,
657 "using 'clone' on a ref-counted pointer"
660 declare_clippy_lint! {
661 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
663 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
664 /// cloning the underlying `T`.
666 /// **Known problems:** None.
673 /// let z = y.clone();
674 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
677 pub CLONE_DOUBLE_REF,
679 "using `clone` on `&&T`"
682 declare_clippy_lint! {
683 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
684 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
686 /// **Why is this bad?** This bypasses the specialized implementation of
687 /// `ToString` and instead goes through the more expensive string formatting
690 /// **Known problems:** None.
694 /// // Generic implementation for `T: Display` is used (slow)
695 /// ["foo", "bar"].iter().map(|s| s.to_string());
697 /// // OK, the specialized impl is used
698 /// ["foo", "bar"].iter().map(|&s| s.to_string());
700 pub INEFFICIENT_TO_STRING,
702 "using `to_string` on `&&T` where `T: ToString`"
705 declare_clippy_lint! {
706 /// **What it does:** Checks for `new` not returning `Self`.
708 /// **Why is this bad?** As a convention, `new` methods are used to make a new
709 /// instance of a type.
711 /// **Known problems:** None.
716 /// # struct NotAFoo;
718 /// fn new() -> NotAFoo {
725 "not returning `Self` in a `new` method"
728 declare_clippy_lint! {
729 /// **What it does:** Checks for string methods that receive a single-character
730 /// `str` as an argument, e.g., `_.split("x")`.
732 /// **Why is this bad?** Performing these methods using a `char` is faster than
735 /// **Known problems:** Does not catch multi-byte unicode characters.
738 /// `_.split("x")` could be `_.split('x')`
739 pub SINGLE_CHAR_PATTERN,
741 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
744 declare_clippy_lint! {
745 /// **What it does:** Checks for getting the inner pointer of a temporary
748 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
749 /// as the `CString` is alive.
751 /// **Known problems:** None.
755 /// # use std::ffi::CString;
756 /// # fn call_some_ffi_func(_: *const i8) {}
758 /// let c_str = CString::new("foo").unwrap().as_ptr();
760 /// call_some_ffi_func(c_str);
763 /// Here `c_str` point to a freed address. The correct use would be:
765 /// # use std::ffi::CString;
766 /// # fn call_some_ffi_func(_: *const i8) {}
768 /// let c_str = CString::new("foo").unwrap();
770 /// call_some_ffi_func(c_str.as_ptr());
773 pub TEMPORARY_CSTRING_AS_PTR,
775 "getting the inner pointer of a temporary `CString`"
778 declare_clippy_lint! {
779 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
781 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
782 /// actually intend to panic.
784 /// **Known problems:** None.
787 /// ```rust,should_panic
788 /// for x in (0..100).step_by(0) {
792 pub ITERATOR_STEP_BY_ZERO,
794 "using `Iterator::step_by(0)`, which will panic at runtime"
797 declare_clippy_lint! {
798 /// **What it does:** Checks for the use of `iter.nth(0)`.
800 /// **Why is this bad?** `iter.next()` is equivalent to
801 /// `iter.nth(0)`, as they both consume the next element,
802 /// but is more readable.
804 /// **Known problems:** None.
809 /// # use std::collections::HashSet;
811 /// # let mut s = HashSet::new();
813 /// let x = s.iter().nth(0);
816 /// # let mut s = HashSet::new();
818 /// let x = s.iter().next();
822 "replace `iter.nth(0)` with `iter.next()`"
825 declare_clippy_lint! {
826 /// **What it does:** Checks for use of `.iter().nth()` (and the related
827 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
829 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
832 /// **Known problems:** None.
836 /// let some_vec = vec![0, 1, 2, 3];
837 /// let bad_vec = some_vec.iter().nth(3);
838 /// let bad_slice = &some_vec[..].iter().nth(3);
840 /// The correct use would be:
842 /// let some_vec = vec![0, 1, 2, 3];
843 /// let bad_vec = some_vec.get(3);
844 /// let bad_slice = &some_vec[..].get(3);
848 "using `.iter().nth()` on a standard library type with O(1) element access"
851 declare_clippy_lint! {
852 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
854 /// **Why is this bad?** `.nth(x)` is cleaner
856 /// **Known problems:** None.
860 /// let some_vec = vec![0, 1, 2, 3];
861 /// let bad_vec = some_vec.iter().skip(3).next();
862 /// let bad_slice = &some_vec[..].iter().skip(3).next();
864 /// The correct use would be:
866 /// let some_vec = vec![0, 1, 2, 3];
867 /// let bad_vec = some_vec.iter().nth(3);
868 /// let bad_slice = &some_vec[..].iter().nth(3);
872 "using `.skip(x).next()` on an iterator"
875 declare_clippy_lint! {
876 /// **What it does:** Checks for use of `.get().unwrap()` (or
877 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
879 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
882 /// **Known problems:** Not a replacement for error handling: Using either
883 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
884 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
885 /// temporary placeholder for dealing with the `Option` type, then this does
886 /// not mitigate the need for error handling. If there is a chance that `.get()`
887 /// will be `None` in your program, then it is advisable that the `None` case
888 /// is handled in a future refactor instead of using `.unwrap()` or the Index
893 /// let mut some_vec = vec![0, 1, 2, 3];
894 /// let last = some_vec.get(3).unwrap();
895 /// *some_vec.get_mut(0).unwrap() = 1;
897 /// The correct use would be:
899 /// let mut some_vec = vec![0, 1, 2, 3];
900 /// let last = some_vec[3];
905 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
908 declare_clippy_lint! {
909 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
910 /// `&str` or `String`.
912 /// **Why is this bad?** `.push_str(s)` is clearer
914 /// **Known problems:** None.
919 /// let def = String::from("def");
920 /// let mut s = String::new();
921 /// s.extend(abc.chars());
922 /// s.extend(def.chars());
924 /// The correct use would be:
927 /// let def = String::from("def");
928 /// let mut s = String::new();
930 /// s.push_str(&def);
932 pub STRING_EXTEND_CHARS,
934 "using `x.extend(s.chars())` where s is a `&str` or `String`"
937 declare_clippy_lint! {
938 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
941 /// **Why is this bad?** `.to_vec()` is clearer
943 /// **Known problems:** None.
947 /// let s = [1, 2, 3, 4, 5];
948 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
950 /// The better use would be:
952 /// let s = [1, 2, 3, 4, 5];
953 /// let s2: Vec<isize> = s.to_vec();
955 pub ITER_CLONED_COLLECT,
957 "using `.cloned().collect()` on slice to create a `Vec`"
960 declare_clippy_lint! {
961 /// **What it does:** Checks for usage of `.chars().last()` or
962 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
964 /// **Why is this bad?** Readability, this can be written more concisely as
965 /// `_.ends_with(_)`.
967 /// **Known problems:** None.
971 /// # let name = "_";
972 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
977 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
980 declare_clippy_lint! {
981 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
982 /// types before and after the call are the same.
984 /// **Why is this bad?** The call is unnecessary.
986 /// **Known problems:** None.
990 /// # fn do_stuff(x: &[i32]) {}
991 /// let x: &[i32] = &[1, 2, 3, 4, 5];
992 /// do_stuff(x.as_ref());
994 /// The correct use would be:
996 /// # fn do_stuff(x: &[i32]) {}
997 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1002 "using `as_ref` where the types before and after the call are the same"
1005 declare_clippy_lint! {
1006 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1007 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1008 /// `sum` or `product`.
1010 /// **Why is this bad?** Readability.
1012 /// **Known problems:** False positive in pattern guards. Will be resolved once
1013 /// non-lexical lifetimes are stable.
1017 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1019 /// This could be written as:
1021 /// let _ = (0..3).any(|x| x > 2);
1023 pub UNNECESSARY_FOLD,
1025 "using `fold` when a more succinct alternative exists"
1028 declare_clippy_lint! {
1029 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1030 /// More specifically it checks if the closure provided is only performing one of the
1031 /// filter or map operations and suggests the appropriate option.
1033 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1034 /// operation is being performed.
1036 /// **Known problems:** None
1040 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1042 /// As there is no transformation of the argument this could be written as:
1044 /// let _ = (0..3).filter(|&x| x > 2);
1048 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1050 /// As there is no conditional check on the argument this could be written as:
1052 /// let _ = (0..4).map(|x| x + 1);
1054 pub UNNECESSARY_FILTER_MAP,
1056 "using `filter_map` when a more succinct alternative exists"
1059 declare_clippy_lint! {
1060 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1063 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1064 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1065 /// `iter_mut` directly.
1067 /// **Known problems:** None
1072 /// let _ = (&vec![3, 4, 5]).into_iter();
1074 pub INTO_ITER_ON_REF,
1076 "using `.into_iter()` on a reference"
1079 declare_clippy_lint! {
1080 /// **What it does:** Checks for calls to `map` followed by a `count`.
1082 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1083 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1084 /// drive the iterator to completion, you can just use `for_each` instead.
1086 /// **Known problems:** None
1091 /// let _ = (0..3).map(|x| x + 2).count();
1095 "suspicious usage of map"
1098 declare_clippy_lint! {
1099 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1101 /// **Why is this bad?** For most types, this is undefined behavior.
1103 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1104 /// of `MaybeUninit`. There may be other types that allow uninitialized
1105 /// data, but those are not yet rigorously defined.
1110 /// // Beware the UB
1111 /// use std::mem::MaybeUninit;
1113 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1116 /// Note that the following is OK:
1119 /// use std::mem::MaybeUninit;
1121 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1122 /// MaybeUninit::uninit().assume_init()
1125 pub UNINIT_ASSUMED_INIT,
1127 "`MaybeUninit::uninit().assume_init()`"
1130 declare_clippy_lint! {
1131 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1133 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1138 /// # let y: u32 = 0;
1139 /// # let x: u32 = 100;
1140 /// let add = x.checked_add(y).unwrap_or(u32::max_value());
1141 /// let sub = x.checked_sub(y).unwrap_or(u32::min_value());
1144 /// can be written using dedicated methods for saturating addition/subtraction as:
1147 /// # let y: u32 = 0;
1148 /// # let x: u32 = 100;
1149 /// let add = x.saturating_add(y);
1150 /// let sub = x.saturating_sub(y);
1152 pub MANUAL_SATURATING_ARITHMETIC,
1154 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1157 declare_clippy_lint! {
1158 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1159 /// zero-sized types
1161 /// **Why is this bad?** This is a no-op, and likely unintended
1163 /// **Known problems:** None
1167 /// unsafe { (&() as *const ()).offset(1) };
1171 "Check for offset calculations on raw pointers to zero-sized types"
1174 declare_clippy_lint! {
1175 /// **What it does:** Checks for `FileType::is_file()`.
1177 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1178 /// they are testing whether a path is something they can get bytes from. But
1179 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1180 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1186 /// let metadata = std::fs::metadata("foo.txt")?;
1187 /// let filetype = metadata.file_type();
1189 /// if filetype.is_file() {
1192 /// # Ok::<_, std::io::Error>(())
1196 /// should be written as:
1200 /// let metadata = std::fs::metadata("foo.txt")?;
1201 /// let filetype = metadata.file_type();
1203 /// if !filetype.is_dir() {
1206 /// # Ok::<_, std::io::Error>(())
1209 pub FILETYPE_IS_FILE,
1211 "`FileType::is_file` is not recommended to test for readable file type"
1214 declare_clippy_lint! {
1215 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1217 /// **Why is this bad?** Readability, this can be written more concisely as a
1218 /// single method call.
1220 /// **Known problems:** None.
1224 /// # let opt = Some("".to_string());
1225 /// opt.as_ref().map(String::as_str)
1228 /// Can be written as
1230 /// # let opt = Some("".to_string());
1234 pub OPTION_AS_REF_DEREF,
1236 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1239 declare_lint_pass!(Methods => [
1244 SHOULD_IMPLEMENT_TRAIT,
1245 WRONG_SELF_CONVENTION,
1246 WRONG_PUB_SELF_CONVENTION,
1248 OPTION_MAP_UNWRAP_OR,
1249 OPTION_MAP_UNWRAP_OR_ELSE,
1250 RESULT_MAP_UNWRAP_OR_ELSE,
1252 OPTION_AND_THEN_SOME,
1260 INEFFICIENT_TO_STRING,
1262 SINGLE_CHAR_PATTERN,
1264 TEMPORARY_CSTRING_AS_PTR,
1272 ITERATOR_STEP_BY_ZERO,
1277 STRING_EXTEND_CHARS,
1278 ITER_CLONED_COLLECT,
1281 UNNECESSARY_FILTER_MAP,
1284 UNINIT_ASSUMED_INIT,
1285 MANUAL_SATURATING_ARITHMETIC,
1288 OPTION_AS_REF_DEREF,
1291 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
1292 #[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
1293 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
1294 if in_macro(expr.span) {
1298 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1299 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1300 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1302 match method_names.as_slice() {
1303 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1304 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1305 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1306 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1307 ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1308 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1309 ["unwrap_or_else", "map"] => lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]),
1310 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1311 ["and_then", ..] => lint_option_and_then_some(cx, expr, arg_lists[0]),
1312 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1313 ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1314 ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
1315 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1316 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
1317 ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
1318 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1319 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1320 ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1321 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1322 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1323 ["is_some", "position"] => {
1324 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1326 ["is_some", "rposition"] => {
1327 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1329 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1330 ["as_ptr", "unwrap"] | ["as_ptr", "expect"] => {
1331 lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0])
1333 ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1334 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1335 ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1336 ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1337 ["next", "skip"] => lint_iter_skip_next(cx, expr),
1338 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1339 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1340 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1341 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1342 ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
1343 ["count", "map"] => lint_suspicious_map(cx, expr),
1344 ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1345 ["unwrap_or", arith @ "checked_add"]
1346 | ["unwrap_or", arith @ "checked_sub"]
1347 | ["unwrap_or", arith @ "checked_mul"] => {
1348 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1350 ["add"] | ["offset"] | ["sub"] | ["wrapping_offset"] | ["wrapping_add"] | ["wrapping_sub"] => {
1351 check_pointer_offset(cx, expr, arg_lists[0])
1353 ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1354 ["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
1355 ["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
1360 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
1361 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1362 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1364 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
1365 if args.len() == 1 && method_call.ident.name == sym!(clone) {
1366 lint_clone_on_copy(cx, expr, &args[0], self_ty);
1367 lint_clone_on_ref_ptr(cx, expr, &args[0]);
1369 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1370 inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1373 match self_ty.kind {
1374 ty::Ref(_, ty, _) if ty.kind == ty::Str => {
1375 for &(method, pos) in &PATTERN_METHODS {
1376 if method_call.ident.name.as_str() == method && args.len() > pos {
1377 lint_single_char_pattern(cx, expr, &args[pos]);
1381 ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
1382 lint_into_iter(cx, expr, self_ty, *method_span);
1387 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1388 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1390 let mut info = BinaryExprInfo {
1394 eq: op.node == hir::BinOpKind::Eq,
1396 lint_binary_expr_with_method_call(cx, &mut info);
1402 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1403 if in_external_macro(cx.sess(), impl_item.span) {
1406 let name = impl_item.ident.name.as_str();
1407 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
1408 let item = cx.tcx.hir().expect_item(parent);
1409 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1410 let ty = cx.tcx.type_of(def_id);
1412 if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind;
1413 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1414 if let hir::ItemKind::Impl{ of_trait: None, .. } = item.kind;
1416 let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
1417 let method_sig = cx.tcx.fn_sig(method_def_id);
1418 let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
1420 let first_arg_ty = &method_sig.inputs().iter().next();
1422 // check conventions w.r.t. conversion method names and predicates
1423 if let Some(first_arg_ty) = first_arg_ty;
1426 if cx.access_levels.is_exported(impl_item.hir_id) {
1427 // check missing trait implementations
1428 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
1429 if name == method_name &&
1430 sig.decl.inputs.len() == n_args &&
1431 out_type.matches(cx, &sig.decl.output) &&
1432 self_kind.matches(cx, ty, first_arg_ty) {
1433 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, impl_item.span, &format!(
1434 "defining a method called `{}` on this type; consider implementing \
1435 the `{}` trait or choosing a less ambiguous name", name, trait_name));
1440 if let Some((ref conv, self_kinds)) = &CONVENTIONS
1442 .find(|(ref conv, _)| conv.check(&name))
1444 if !self_kinds.iter().any(|k| k.matches(cx, ty, first_arg_ty)) {
1445 let lint = if item.vis.node.is_pub() {
1446 WRONG_PUB_SELF_CONVENTION
1448 WRONG_SELF_CONVENTION
1456 "methods called `{}` usually take {}; consider choosing a less \
1461 .map(|k| k.description())
1462 .collect::<Vec<_>>()
1471 if let hir::ImplItemKind::Fn(_, _) = impl_item.kind {
1472 let ret_ty = return_ty(cx, impl_item.hir_id);
1474 // walk the return type and check for Self (this does not check associated types)
1475 if ret_ty.walk().any(|inner_type| same_tys(cx, ty, inner_type)) {
1479 // if return type is impl trait, check the associated types
1480 if let ty::Opaque(def_id, _) = ret_ty.kind {
1481 // one of the associated types must be Self
1482 for predicate in cx.tcx.predicates_of(def_id).predicates {
1484 (Predicate::Projection(poly_projection_predicate), _) => {
1485 let binder = poly_projection_predicate.ty();
1486 let associated_type = binder.skip_binder();
1488 // walk the associated type and check for Self
1489 for inner_type in associated_type.walk() {
1490 if same_tys(cx, ty, inner_type) {
1500 if name == "new" && !same_tys(cx, ret_ty, ty) {
1505 "methods called `new` usually return `Self`",
1512 /// Checks for the `OR_FUN_CALL` lint.
1513 #[allow(clippy::too_many_lines)]
1514 fn lint_or_fun_call<'a, 'tcx>(
1515 cx: &LateContext<'a, 'tcx>,
1516 expr: &hir::Expr<'_>,
1519 args: &'tcx [hir::Expr<'_>],
1521 // Searches an expression for method calls or function calls that aren't ctors
1522 struct FunCallFinder<'a, 'tcx> {
1523 cx: &'a LateContext<'a, 'tcx>,
1527 impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
1528 type Map = Map<'tcx>;
1530 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
1531 let call_found = match &expr.kind {
1532 // ignore enum and struct constructors
1533 hir::ExprKind::Call(..) => !is_ctor_or_promotable_const_function(self.cx, expr),
1534 hir::ExprKind::MethodCall(..) => true,
1543 intravisit::walk_expr(self, expr);
1547 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1548 intravisit::NestedVisitorMap::None
1552 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1553 fn check_unwrap_or_default(
1554 cx: &LateContext<'_, '_>,
1556 fun: &hir::Expr<'_>,
1557 self_expr: &hir::Expr<'_>,
1558 arg: &hir::Expr<'_>,
1564 if name == "unwrap_or";
1565 if let hir::ExprKind::Path(ref qpath) = fun.kind;
1566 let path = &*last_path_segment(qpath).ident.as_str();
1567 if ["default", "new"].contains(&path);
1568 let arg_ty = cx.tables.expr_ty(arg);
1569 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1570 if implements_trait(cx, arg_ty, default_trait_id, &[]);
1573 let mut applicability = Applicability::MachineApplicable;
1578 &format!("use of `{}` followed by a call to `{}`", name, path),
1581 "{}.unwrap_or_default()",
1582 snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
1594 /// Checks for `*or(foo())`.
1595 #[allow(clippy::too_many_arguments)]
1596 fn check_general_case<'a, 'tcx>(
1597 cx: &LateContext<'a, 'tcx>,
1601 self_expr: &hir::Expr<'_>,
1602 arg: &'tcx hir::Expr<'_>,
1606 // (path, fn_has_argument, methods, suffix)
1607 let know_types: &[(&[_], _, &[_], _)] = &[
1608 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1609 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1610 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1611 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1615 if know_types.iter().any(|k| k.2.contains(&name));
1617 let mut finder = FunCallFinder { cx: &cx, found: false };
1618 if { finder.visit_expr(&arg); finder.found };
1619 if !contains_return(&arg);
1621 let self_ty = cx.tables.expr_ty(self_expr);
1623 if let Some(&(_, fn_has_arguments, poss, suffix)) =
1624 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
1626 if poss.contains(&name);
1629 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1630 (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1631 (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1632 (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1634 let span_replace_word = method_span.with_hi(span.hi());
1639 &format!("use of `{}` followed by a function call", name),
1641 format!("{}_{}({})", name, suffix, sugg),
1642 Applicability::HasPlaceholders,
1648 if args.len() == 2 {
1649 match args[1].kind {
1650 hir::ExprKind::Call(ref fun, ref or_args) => {
1651 let or_has_args = !or_args.is_empty();
1652 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1665 hir::ExprKind::MethodCall(_, span, ref or_args) => check_general_case(
1672 !or_args.is_empty(),
1680 /// Checks for the `EXPECT_FUN_CALL` lint.
1681 #[allow(clippy::too_many_lines)]
1682 fn lint_expect_fun_call(
1683 cx: &LateContext<'_, '_>,
1684 expr: &hir::Expr<'_>,
1687 args: &[hir::Expr<'_>],
1689 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1691 fn get_arg_root<'a>(cx: &LateContext<'_, '_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1692 let mut arg_root = arg;
1694 arg_root = match &arg_root.kind {
1695 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1696 hir::ExprKind::MethodCall(method_name, _, call_args) => {
1697 if call_args.len() == 1
1698 && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1700 let arg_type = cx.tables.expr_ty(&call_args[0]);
1701 let base_type = walk_ptrs_ty(arg_type);
1702 base_type.kind == ty::Str || match_type(cx, base_type, &paths::STRING)
1716 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1717 // converted to string.
1718 fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1719 let arg_ty = cx.tables.expr_ty(arg);
1720 if match_type(cx, arg_ty, &paths::STRING) {
1723 if let ty::Ref(_, ty, ..) = arg_ty.kind {
1724 if ty.kind == ty::Str && can_be_static_str(cx, arg) {
1731 // Check if an expression could have type `&'static str`, knowing that it
1732 // has type `&str` for some lifetime.
1733 fn can_be_static_str(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1735 hir::ExprKind::Lit(_) => true,
1736 hir::ExprKind::Call(fun, _) => {
1737 if let hir::ExprKind::Path(ref p) = fun.kind {
1738 match cx.tables.qpath_res(p, fun.hir_id) {
1739 hir::def::Res::Def(hir::def::DefKind::Fn, def_id)
1740 | hir::def::Res::Def(hir::def::DefKind::AssocFn, def_id) => matches!(
1741 cx.tcx.fn_sig(def_id).output().skip_binder().kind,
1742 ty::Ref(ty::ReStatic, ..)
1750 hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(arg.hir_id).map_or(false, |method_id| {
1752 cx.tcx.fn_sig(method_id).output().skip_binder().kind,
1753 ty::Ref(ty::ReStatic, ..)
1756 hir::ExprKind::Path(ref p) => match cx.tables.qpath_res(p, arg.hir_id) {
1757 hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _) => true,
1764 fn generate_format_arg_snippet(
1765 cx: &LateContext<'_, '_>,
1767 applicability: &mut Applicability,
1770 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1771 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1772 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
1777 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1785 fn is_call(node: &hir::ExprKind<'_>) -> bool {
1787 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
1790 hir::ExprKind::Call(..)
1791 | hir::ExprKind::MethodCall(..)
1792 // These variants are debatable or require further examination
1793 | hir::ExprKind::Match(..)
1794 | hir::ExprKind::Block{ .. } => true,
1799 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
1803 let receiver_type = cx.tables.expr_ty_adjusted(&args[0]);
1804 let closure_args = if match_type(cx, receiver_type, &paths::OPTION) {
1806 } else if match_type(cx, receiver_type, &paths::RESULT) {
1812 let arg_root = get_arg_root(cx, &args[1]);
1814 let span_replace_word = method_span.with_hi(expr.span.hi());
1816 let mut applicability = Applicability::MachineApplicable;
1818 //Special handling for `format!` as arg_root
1820 if let hir::ExprKind::Block(block, None) = &arg_root.kind;
1821 if block.stmts.len() == 1;
1822 if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
1823 if let Some(arg_root) = &local.init;
1824 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
1825 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
1826 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
1828 let fmt_spec = &format_args[0];
1829 let fmt_args = &format_args[1];
1831 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1833 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1835 let sugg = args.join(", ");
1841 &format!("use of `{}` followed by a function call", name),
1843 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1851 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1852 if requires_to_string(cx, arg_root) {
1853 arg_root_snippet.to_mut().push_str(".to_string()");
1860 &format!("use of `{}` followed by a function call", name),
1862 format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1867 /// Checks for the `CLONE_ON_COPY` lint.
1868 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
1869 let ty = cx.tables.expr_ty(expr);
1870 if let ty::Ref(_, inner, _) = arg_ty.kind {
1871 if let ty::Ref(_, innermost, _) = inner.kind {
1876 "using `clone` on a double-reference; \
1877 this will copy the reference instead of cloning the inner type",
1879 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1880 let mut ty = innermost;
1882 while let ty::Ref(_, inner, _) = ty.kind {
1886 let refs: String = iter::repeat('&').take(n + 1).collect();
1887 let derefs: String = iter::repeat('*').take(n).collect();
1888 let explicit = format!("{}{}::clone({})", refs, ty, snip);
1891 "try dereferencing it",
1892 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1893 Applicability::MaybeIncorrect,
1897 "or try being explicit about what type to clone",
1899 Applicability::MaybeIncorrect,
1904 return; // don't report clone_on_copy
1908 if is_copy(cx, ty) {
1910 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1911 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
1912 match &cx.tcx.hir().get(parent) {
1913 hir::Node::Expr(parent) => match parent.kind {
1914 // &*x is a nop, &x.clone() is not
1915 hir::ExprKind::AddrOf(..) |
1916 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1917 hir::ExprKind::MethodCall(..) => return,
1920 hir::Node::Stmt(stmt) => {
1921 if let hir::StmtKind::Local(ref loc) = stmt.kind {
1922 if let hir::PatKind::Ref(..) = loc.pat.kind {
1923 // let ref y = *x borrows x, let ref y = x.clone() does not
1931 // x.clone() might have dereferenced x, possibly through Deref impls
1932 if cx.tables.expr_ty(arg) == ty {
1933 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1935 let deref_count = cx
1937 .expr_adjustments(arg)
1940 if let ty::adjustment::Adjust::Deref(_) = adj.kind {
1947 let derefs: String = iter::repeat('*').take(deref_count).collect();
1948 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
1953 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1954 if let Some((text, snip)) = snip {
1955 db.span_suggestion(expr.span, text, snip, Applicability::Unspecified);
1961 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
1962 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1964 if let ty::Adt(_, subst) = obj_ty.kind {
1965 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1967 } else if match_type(cx, obj_ty, &paths::ARC) {
1969 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1979 "using `.clone()` on a ref-counted pointer",
1982 "{}::<{}>::clone(&{})",
1985 snippet(cx, arg.span, "_")
1987 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
1992 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1994 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1995 let target = &arglists[0][0];
1996 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
1997 let ref_str = if self_ty.kind == ty::Str {
1999 } else if match_type(cx, self_ty, &paths::STRING) {
2005 let mut applicability = Applicability::MachineApplicable;
2008 STRING_EXTEND_CHARS,
2010 "calling `.extend(_.chars())`",
2013 "{}.push_str({}{})",
2014 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
2016 snippet_with_applicability(cx, target.span, "_", &mut applicability)
2023 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2024 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
2025 if match_type(cx, obj_ty, &paths::STRING) {
2026 lint_string_extend(cx, expr, args);
2030 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2032 let source_type = cx.tables.expr_ty(source);
2033 if let ty::Adt(def, substs) = source_type.kind;
2034 if match_def_path(cx, def.did, &paths::RESULT);
2035 if match_type(cx, substs.type_at(0), &paths::CSTRING);
2039 TEMPORARY_CSTRING_AS_PTR,
2041 "you are getting the inner pointer of a temporary `CString`",
2043 db.note("that pointer will be invalid outside this expression");
2044 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2050 fn lint_iter_cloned_collect<'a, 'tcx>(
2051 cx: &LateContext<'a, 'tcx>,
2052 expr: &hir::Expr<'_>,
2053 iter_args: &'tcx [hir::Expr<'_>],
2056 if is_type_diagnostic_item(cx, cx.tables.expr_ty(expr), Symbol::intern("vec_type"));
2057 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0]));
2058 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2063 ITER_CLONED_COLLECT,
2065 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2068 ".to_vec()".to_string(),
2069 Applicability::MachineApplicable,
2075 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2076 fn check_fold_with_op(
2077 cx: &LateContext<'_, '_>,
2078 expr: &hir::Expr<'_>,
2079 fold_args: &[hir::Expr<'_>],
2082 replacement_method_name: &str,
2083 replacement_has_args: bool,
2086 // Extract the body of the closure passed to fold
2087 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2088 let closure_body = cx.tcx.hir().body(body_id);
2089 let closure_expr = remove_blocks(&closure_body.value);
2091 // Check if the closure body is of the form `acc <op> some_expr(x)`
2092 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2093 if bin_op.node == op;
2095 // Extract the names of the two arguments to the closure
2096 if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2097 if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2099 if match_var(&*left_expr, first_arg_ident);
2100 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2103 let mut applicability = Applicability::MachineApplicable;
2104 let sugg = if replacement_has_args {
2106 "{replacement}(|{s}| {r})",
2107 replacement = replacement_method_name,
2108 s = second_arg_ident,
2109 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2114 replacement = replacement_method_name,
2121 fold_span.with_hi(expr.span.hi()),
2122 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2123 "this `.fold` can be written more succinctly using another method",
2132 // Check that this is a call to Iterator::fold rather than just some function called fold
2133 if !match_trait_method(cx, expr, &paths::ITERATOR) {
2138 fold_args.len() == 3,
2139 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2142 // Check if the first argument to .fold is a suitable literal
2143 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2145 ast::LitKind::Bool(false) => {
2146 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2148 ast::LitKind::Bool(true) => {
2149 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2151 ast::LitKind::Int(0, _) => {
2152 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2154 ast::LitKind::Int(1, _) => {
2155 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2162 fn lint_step_by<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2163 if match_trait_method(cx, expr, &paths::ITERATOR) {
2164 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
2167 ITERATOR_STEP_BY_ZERO,
2169 "Iterator::step_by(0) will panic at runtime",
2175 fn lint_iter_nth<'a, 'tcx>(
2176 cx: &LateContext<'a, 'tcx>,
2177 expr: &hir::Expr<'_>,
2178 nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2181 let iter_args = nth_and_iter_args[1];
2182 let mut_str = if is_mut { "_mut" } else { "" };
2183 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
2185 } else if is_type_diagnostic_item(cx, cx.tables.expr_ty(&iter_args[0]), Symbol::intern("vec_type")) {
2187 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
2190 let nth_args = nth_and_iter_args[0];
2191 lint_iter_nth_zero(cx, expr, &nth_args);
2192 return; // caller is not a type that we want to lint
2199 &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2200 &format!("calling `.get{}()` is both faster and more readable", mut_str),
2204 fn lint_iter_nth_zero<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2206 if match_trait_method(cx, expr, &paths::ITERATOR);
2207 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &nth_args[1]);
2209 let mut applicability = Applicability::MachineApplicable;
2214 "called `.nth(0)` on a `std::iter::Iterator`",
2216 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2223 fn lint_get_unwrap<'a, 'tcx>(
2224 cx: &LateContext<'a, 'tcx>,
2225 expr: &hir::Expr<'_>,
2226 get_args: &'tcx [hir::Expr<'_>],
2229 // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2230 // because they do not implement `IndexMut`
2231 let mut applicability = Applicability::MachineApplicable;
2232 let expr_ty = cx.tables.expr_ty(&get_args[0]);
2233 let get_args_str = if get_args.len() > 1 {
2234 snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
2236 return; // not linting on a .get().unwrap() chain or variant
2239 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2240 needs_ref = get_args_str.parse::<usize>().is_ok();
2242 } else if is_type_diagnostic_item(cx, expr_ty, Symbol::intern("vec_type")) {
2243 needs_ref = get_args_str.parse::<usize>().is_ok();
2245 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
2246 needs_ref = get_args_str.parse::<usize>().is_ok();
2248 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
2251 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2255 return; // caller is not a type that we want to lint
2258 let mut span = expr.span;
2260 // Handle the case where the result is immediately dereferenced
2261 // by not requiring ref and pulling the dereference into the
2265 if let Some(parent) = get_parent_expr(cx, expr);
2266 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2273 let mut_str = if is_mut { "_mut" } else { "" };
2274 let borrow_str = if !needs_ref {
2287 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2288 mut_str, caller_type
2294 snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
2301 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
2302 // lint if caller of skip is an Iterator
2303 if match_trait_method(cx, expr, &paths::ITERATOR) {
2308 "called `skip(x).next()` on an iterator",
2309 "this is more succinctly expressed by calling `nth(x)`",
2314 fn derefs_to_slice<'a, 'tcx>(
2315 cx: &LateContext<'a, 'tcx>,
2316 expr: &'tcx hir::Expr<'tcx>,
2318 ) -> Option<&'tcx hir::Expr<'tcx>> {
2319 fn may_slice<'a>(cx: &LateContext<'_, 'a>, ty: Ty<'a>) -> bool {
2321 ty::Slice(_) => true,
2322 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2323 ty::Adt(..) => is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type")),
2324 ty::Array(_, size) => {
2325 if let Some(size) = size.try_eval_usize(cx.tcx, cx.param_env) {
2331 ty::Ref(_, inner, _) => may_slice(cx, inner),
2336 if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
2337 if path.ident.name == sym!(iter) && may_slice(cx, cx.tables.expr_ty(&args[0])) {
2344 ty::Slice(_) => Some(expr),
2345 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2346 ty::Ref(_, inner, _) => {
2347 if may_slice(cx, inner) {
2358 /// lint use of `unwrap()` for `Option`s and `Result`s
2359 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2360 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
2362 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
2363 Some((OPTION_UNWRAP_USED, "an Option", "None"))
2364 } else if match_type(cx, obj_ty, &paths::RESULT) {
2365 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
2370 if let Some((lint, kind, none_value)) = mess {
2375 &format!("used `unwrap()` on `{}` value", kind,),
2377 "if you don't want to handle the `{}` case gracefully, consider \
2378 using `expect()` to provide a better panic message",
2385 /// lint use of `expect()` for `Option`s and `Result`s
2386 fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2387 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&expect_args[0]));
2389 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
2390 Some((OPTION_EXPECT_USED, "an Option", "None"))
2391 } else if match_type(cx, obj_ty, &paths::RESULT) {
2392 Some((RESULT_EXPECT_USED, "a Result", "Err"))
2397 if let Some((lint, kind, none_value)) = mess {
2402 &format!("used `expect()` on `{}` value", kind,),
2403 &format!("if this value is an `{}`, it will panic", none_value,),
2408 /// lint use of `ok().expect()` for `Result`s
2409 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2411 // lint if the caller of `ok()` is a `Result`
2412 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT);
2413 let result_type = cx.tables.expr_ty(&ok_args[0]);
2414 if let Some(error_type) = get_error_type(cx, result_type);
2415 if has_debug_impl(error_type, cx);
2422 "called `ok().expect()` on a `Result` value",
2423 "you can call `expect()` directly on the `Result`",
2429 /// lint use of `map().flatten()` for `Iterators`
2430 fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2431 // lint if caller of `.map().flatten()` is an Iterator
2432 if match_trait_method(cx, expr, &paths::ITERATOR) {
2433 let msg = "called `map(..).flatten()` on an `Iterator`. \
2434 This is more succinctly expressed by calling `.flat_map(..)`";
2435 let self_snippet = snippet(cx, map_args[0].span, "..");
2436 let func_snippet = snippet(cx, map_args[1].span, "..");
2437 let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
2443 "try using `flat_map` instead",
2445 Applicability::MachineApplicable,
2450 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2451 fn lint_map_unwrap_or_else<'a, 'tcx>(
2452 cx: &LateContext<'a, 'tcx>,
2453 expr: &'tcx hir::Expr<'_>,
2454 map_args: &'tcx [hir::Expr<'_>],
2455 unwrap_args: &'tcx [hir::Expr<'_>],
2457 // lint if the caller of `map()` is an `Option`
2458 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
2459 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
2461 if is_option || is_result {
2462 // Don't make a suggestion that may fail to compile due to mutably borrowing
2463 // the same variable twice.
2464 let map_mutated_vars = mutated_variables(&map_args[0], cx);
2465 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2466 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2467 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2475 let msg = if is_option {
2476 "called `map(f).unwrap_or_else(g)` on an `Option` value. This can be done more directly by calling \
2477 `map_or_else(g, f)` instead"
2479 "called `map(f).unwrap_or_else(g)` on a `Result` value. This can be done more directly by calling \
2480 `.map_or_else(g, f)` instead"
2482 // get snippets for args to map() and unwrap_or_else()
2483 let map_snippet = snippet(cx, map_args[1].span, "..");
2484 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2485 // lint, with note if neither arg is > 1 line and both map() and
2486 // unwrap_or_else() have the same span
2487 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2488 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2489 if same_span && !multiline {
2493 OPTION_MAP_UNWRAP_OR_ELSE
2495 RESULT_MAP_UNWRAP_OR_ELSE
2501 "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
2502 map_snippet, unwrap_snippet,
2505 } else if same_span && multiline {
2509 OPTION_MAP_UNWRAP_OR_ELSE
2511 RESULT_MAP_UNWRAP_OR_ELSE
2520 /// lint use of `_.map_or(None, _)` for `Option`s
2521 fn lint_map_or_none<'a, 'tcx>(
2522 cx: &LateContext<'a, 'tcx>,
2523 expr: &'tcx hir::Expr<'_>,
2524 map_or_args: &'tcx [hir::Expr<'_>],
2526 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
2527 // check if the first non-self argument to map_or() is None
2528 let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2529 match_qpath(qpath, &paths::OPTION_NONE)
2534 if map_or_arg_is_none {
2536 let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \
2537 `and_then(f)` instead";
2538 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
2539 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
2540 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
2546 "try using `and_then` instead",
2548 Applicability::MachineApplicable,
2554 /// Lint use of `_.and_then(|x| Some(y))` for `Option`s
2555 fn lint_option_and_then_some(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2556 const LINT_MSG: &str = "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`";
2557 const NO_OP_MSG: &str = "using `Option.and_then(Some)`, which is a no-op";
2559 let ty = cx.tables.expr_ty(&args[0]);
2560 if !match_type(cx, ty, &paths::OPTION) {
2564 match args[1].kind {
2565 hir::ExprKind::Closure(_, _, body_id, closure_args_span, _) => {
2566 let closure_body = cx.tcx.hir().body(body_id);
2567 let closure_expr = remove_blocks(&closure_body.value);
2569 if let hir::ExprKind::Call(ref some_expr, ref some_args) = closure_expr.kind;
2570 if let hir::ExprKind::Path(ref qpath) = some_expr.kind;
2571 if match_qpath(qpath, &paths::OPTION_SOME);
2572 if some_args.len() == 1;
2574 let inner_expr = &some_args[0];
2576 if contains_return(inner_expr) {
2580 let some_inner_snip = if inner_expr.span.from_expansion() {
2581 snippet_with_macro_callsite(cx, inner_expr.span, "_")
2583 snippet(cx, inner_expr.span, "_")
2586 let closure_args_snip = snippet(cx, closure_args_span, "..");
2587 let option_snip = snippet(cx, args[0].span, "..");
2588 let note = format!("{}.map({} {})", option_snip, closure_args_snip, some_inner_snip);
2591 OPTION_AND_THEN_SOME,
2596 Applicability::MachineApplicable,
2601 // `_.and_then(Some)` case, which is no-op.
2602 hir::ExprKind::Path(ref qpath) => {
2603 if match_qpath(qpath, &paths::OPTION_SOME) {
2604 let option_snip = snippet(cx, args[0].span, "..");
2605 let note = format!("{}", option_snip);
2608 OPTION_AND_THEN_SOME,
2611 "use the expression directly",
2613 Applicability::MachineApplicable,
2621 /// lint use of `filter().next()` for `Iterators`
2622 fn lint_filter_next<'a, 'tcx>(
2623 cx: &LateContext<'a, 'tcx>,
2624 expr: &'tcx hir::Expr<'_>,
2625 filter_args: &'tcx [hir::Expr<'_>],
2627 // lint if caller of `.filter().next()` is an Iterator
2628 if match_trait_method(cx, expr, &paths::ITERATOR) {
2629 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2630 `.find(p)` instead.";
2631 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2632 if filter_snippet.lines().count() <= 1 {
2633 // add note if not multi-line
2640 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2643 span_lint(cx, FILTER_NEXT, expr.span, msg);
2648 /// lint use of `skip_while().next()` for `Iterators`
2649 fn lint_skip_while_next<'a, 'tcx>(
2650 cx: &LateContext<'a, 'tcx>,
2651 expr: &'tcx hir::Expr<'_>,
2652 _skip_while_args: &'tcx [hir::Expr<'_>],
2654 // lint if caller of `.skip_while().next()` is an Iterator
2655 if match_trait_method(cx, expr, &paths::ITERATOR) {
2660 "called `skip_while(p).next()` on an `Iterator`",
2661 "this is more succinctly expressed by calling `.find(!p)` instead",
2666 /// lint use of `filter().map()` for `Iterators`
2667 fn lint_filter_map<'a, 'tcx>(
2668 cx: &LateContext<'a, 'tcx>,
2669 expr: &'tcx hir::Expr<'_>,
2670 _filter_args: &'tcx [hir::Expr<'_>],
2671 _map_args: &'tcx [hir::Expr<'_>],
2673 // lint if caller of `.filter().map()` is an Iterator
2674 if match_trait_method(cx, expr, &paths::ITERATOR) {
2675 let msg = "called `filter(p).map(q)` on an `Iterator`";
2676 let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2677 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2681 /// lint use of `filter_map().next()` for `Iterators`
2682 fn lint_filter_map_next<'a, 'tcx>(
2683 cx: &LateContext<'a, 'tcx>,
2684 expr: &'tcx hir::Expr<'_>,
2685 filter_args: &'tcx [hir::Expr<'_>],
2687 if match_trait_method(cx, expr, &paths::ITERATOR) {
2688 let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2689 `.find_map(p)` instead.";
2690 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2691 if filter_snippet.lines().count() <= 1 {
2698 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2701 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2706 /// lint use of `find().map()` for `Iterators`
2707 fn lint_find_map<'a, 'tcx>(
2708 cx: &LateContext<'a, 'tcx>,
2709 expr: &'tcx hir::Expr<'_>,
2710 _find_args: &'tcx [hir::Expr<'_>],
2711 map_args: &'tcx [hir::Expr<'_>],
2713 // lint if caller of `.filter().map()` is an Iterator
2714 if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2715 let msg = "called `find(p).map(q)` on an `Iterator`";
2716 let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2717 span_lint_and_help(cx, FIND_MAP, expr.span, msg, hint);
2721 /// lint use of `filter_map().map()` for `Iterators`
2722 fn lint_filter_map_map<'a, 'tcx>(
2723 cx: &LateContext<'a, 'tcx>,
2724 expr: &'tcx hir::Expr<'_>,
2725 _filter_args: &'tcx [hir::Expr<'_>],
2726 _map_args: &'tcx [hir::Expr<'_>],
2728 // lint if caller of `.filter().map()` is an Iterator
2729 if match_trait_method(cx, expr, &paths::ITERATOR) {
2730 let msg = "called `filter_map(p).map(q)` on an `Iterator`";
2731 let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2732 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2736 /// lint use of `filter().flat_map()` for `Iterators`
2737 fn lint_filter_flat_map<'a, 'tcx>(
2738 cx: &LateContext<'a, 'tcx>,
2739 expr: &'tcx hir::Expr<'_>,
2740 _filter_args: &'tcx [hir::Expr<'_>],
2741 _map_args: &'tcx [hir::Expr<'_>],
2743 // lint if caller of `.filter().flat_map()` is an Iterator
2744 if match_trait_method(cx, expr, &paths::ITERATOR) {
2745 let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
2746 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2747 and filtering by returning `iter::empty()`";
2748 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2752 /// lint use of `filter_map().flat_map()` for `Iterators`
2753 fn lint_filter_map_flat_map<'a, 'tcx>(
2754 cx: &LateContext<'a, 'tcx>,
2755 expr: &'tcx hir::Expr<'_>,
2756 _filter_args: &'tcx [hir::Expr<'_>],
2757 _map_args: &'tcx [hir::Expr<'_>],
2759 // lint if caller of `.filter_map().flat_map()` is an Iterator
2760 if match_trait_method(cx, expr, &paths::ITERATOR) {
2761 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
2762 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2763 and filtering by returning `iter::empty()`";
2764 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2768 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2769 fn lint_flat_map_identity<'a, 'tcx>(
2770 cx: &LateContext<'a, 'tcx>,
2771 expr: &'tcx hir::Expr<'_>,
2772 flat_map_args: &'tcx [hir::Expr<'_>],
2773 flat_map_span: Span,
2775 if match_trait_method(cx, expr, &paths::ITERATOR) {
2776 let arg_node = &flat_map_args[1].kind;
2778 let apply_lint = |message: &str| {
2782 flat_map_span.with_hi(expr.span.hi()),
2785 "flatten()".to_string(),
2786 Applicability::MachineApplicable,
2791 if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
2792 let body = cx.tcx.hir().body(*body_id);
2794 if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
2795 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
2797 if path.segments.len() == 1;
2798 if path.segments[0].ident.as_str() == binding_ident.as_str();
2801 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
2806 if let hir::ExprKind::Path(ref qpath) = arg_node;
2808 if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2811 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
2817 /// lint searching an Iterator followed by `is_some()`
2818 fn lint_search_is_some<'a, 'tcx>(
2819 cx: &LateContext<'a, 'tcx>,
2820 expr: &'tcx hir::Expr<'_>,
2821 search_method: &str,
2822 search_args: &'tcx [hir::Expr<'_>],
2823 is_some_args: &'tcx [hir::Expr<'_>],
2826 // lint if caller of search is an Iterator
2827 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2829 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2830 expressed by calling `any()`.",
2833 let search_snippet = snippet(cx, search_args[1].span, "..");
2834 if search_snippet.lines().count() <= 1 {
2835 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2836 // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
2837 let any_search_snippet = if_chain! {
2838 if search_method == "find";
2839 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
2840 let closure_body = cx.tcx.hir().body(body_id);
2841 if let Some(closure_arg) = closure_body.params.get(0);
2843 if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
2844 Some(search_snippet.replacen('&', "", 1))
2845 } else if let Some(name) = get_arg_name(&closure_arg.pat) {
2846 Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
2854 // add note if not multi-line
2858 method_span.with_hi(expr.span.hi()),
2863 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2865 Applicability::MachineApplicable,
2868 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2873 /// Used for `lint_binary_expr_with_method_call`.
2874 #[derive(Copy, Clone)]
2875 struct BinaryExprInfo<'a> {
2876 expr: &'a hir::Expr<'a>,
2877 chain: &'a hir::Expr<'a>,
2878 other: &'a hir::Expr<'a>,
2882 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2883 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
2884 macro_rules! lint_with_both_lhs_and_rhs {
2885 ($func:ident, $cx:expr, $info:ident) => {
2886 if !$func($cx, $info) {
2887 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2888 if $func($cx, $info) {
2895 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2896 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2897 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2898 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2901 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2903 cx: &LateContext<'_, '_>,
2904 info: &BinaryExprInfo<'_>,
2905 chain_methods: &[&str],
2906 lint: &'static Lint,
2910 if let Some(args) = method_chain_args(info.chain, chain_methods);
2911 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2912 if arg_char.len() == 1;
2913 if let hir::ExprKind::Path(ref qpath) = fun.kind;
2914 if let Some(segment) = single_segment_path(qpath);
2915 if segment.ident.name == sym!(Some);
2917 let mut applicability = Applicability::MachineApplicable;
2918 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
2920 if self_ty.kind != ty::Str {
2928 &format!("you should use the `{}` method", suggest),
2930 format!("{}{}.{}({})",
2931 if info.eq { "" } else { "!" },
2932 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2934 snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
2945 /// Checks for the `CHARS_NEXT_CMP` lint.
2946 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2947 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2950 /// Checks for the `CHARS_LAST_CMP` lint.
2951 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2952 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2955 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2959 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2960 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
2961 cx: &LateContext<'a, 'tcx>,
2962 info: &BinaryExprInfo<'_>,
2963 chain_methods: &[&str],
2964 lint: &'static Lint,
2968 if let Some(args) = method_chain_args(info.chain, chain_methods);
2969 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2970 if let ast::LitKind::Char(c) = lit.node;
2972 let mut applicability = Applicability::MachineApplicable;
2977 &format!("you should use the `{}` method", suggest),
2979 format!("{}{}.{}('{}')",
2980 if info.eq { "" } else { "!" },
2981 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2994 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2995 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2996 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
2999 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3000 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3001 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3004 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3008 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3009 fn lint_single_char_pattern<'a, 'tcx>(
3010 cx: &LateContext<'a, 'tcx>,
3011 _expr: &'tcx hir::Expr<'_>,
3012 arg: &'tcx hir::Expr<'_>,
3015 if let hir::ExprKind::Lit(lit) = &arg.kind;
3016 if let ast::LitKind::Str(r, style) = lit.node;
3017 if r.as_str().len() == 1;
3019 let mut applicability = Applicability::MachineApplicable;
3020 let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
3021 let ch = if let ast::StrStyle::Raw(nhash) = style {
3022 let nhash = nhash as usize;
3023 // for raw string: r##"a"##
3024 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3026 // for regular string: "a"
3027 &snip[1..(snip.len() - 1)]
3029 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3032 SINGLE_CHAR_PATTERN,
3034 "single-character string constant used as pattern",
3035 "try using a `char` instead",
3043 /// Checks for the `USELESS_ASREF` lint.
3044 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3045 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3046 // check if the call is to the actual `AsRef` or `AsMut` trait
3047 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3048 // check if the type after `as_ref` or `as_mut` is the same as before
3049 let recvr = &as_ref_args[0];
3050 let rcv_ty = cx.tables.expr_ty(recvr);
3051 let res_ty = cx.tables.expr_ty(expr);
3052 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3053 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3054 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3055 // allow the `as_ref` or `as_mut` if it is followed by another method call
3057 if let Some(parent) = get_parent_expr(cx, expr);
3058 if let hir::ExprKind::MethodCall(_, ref span, _) = parent.kind;
3059 if span != &expr.span;
3065 let mut applicability = Applicability::MachineApplicable;
3070 &format!("this call to `{}` does nothing", call_name),
3072 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
3079 fn ty_has_iter_method(cx: &LateContext<'_, '_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3080 has_iter_method(cx, self_ref_ty).map(|ty_name| {
3081 let mutbl = match self_ref_ty.kind {
3082 ty::Ref(_, _, mutbl) => mutbl,
3083 _ => unreachable!(),
3085 let method_name = match mutbl {
3086 hir::Mutability::Not => "iter",
3087 hir::Mutability::Mut => "iter_mut",
3089 (ty_name, method_name)
3093 fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3094 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3097 if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3103 "this `.into_iter()` call is equivalent to `.{}()` and will not move the `{}`",
3107 method_name.to_string(),
3108 Applicability::MachineApplicable,
3113 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3114 fn lint_maybe_uninit(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3116 if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3118 if let hir::ExprKind::Path(ref path) = callee.kind;
3119 if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3120 if !is_maybe_uninit_ty_valid(cx, cx.tables.expr_ty_adjusted(outer));
3124 UNINIT_ASSUMED_INIT,
3126 "this call for this type may be undefined behavior"
3132 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
3134 ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3135 ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3136 ty::Adt(ref adt, _) => {
3137 // needs to be a MaybeUninit
3138 match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT)
3144 fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
3149 "this call to `map()` won't have an effect on the call to `count()`",
3150 "make sure you did not confuse `map` with `filter` or `for_each`",
3154 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3155 fn lint_option_as_ref_deref<'a, 'tcx>(
3156 cx: &LateContext<'a, 'tcx>,
3157 expr: &hir::Expr<'_>,
3158 as_ref_args: &[hir::Expr<'_>],
3159 map_args: &[hir::Expr<'_>],
3162 let option_ty = cx.tables.expr_ty(&as_ref_args[0]);
3163 if !match_type(cx, option_ty, &paths::OPTION) {
3167 let deref_aliases: [&[&str]; 9] = [
3168 &paths::DEREF_TRAIT_METHOD,
3169 &paths::DEREF_MUT_TRAIT_METHOD,
3170 &paths::CSTRING_AS_C_STR,
3171 &paths::OS_STRING_AS_OS_STR,
3172 &paths::PATH_BUF_AS_PATH,
3173 &paths::STRING_AS_STR,
3174 &paths::STRING_AS_MUT_STR,
3175 &paths::VEC_AS_SLICE,
3176 &paths::VEC_AS_MUT_SLICE,
3179 let is_deref = match map_args[1].kind {
3180 hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3181 hir::ExprKind::Closure(_, _, body_id, _, _) => {
3182 let closure_body = cx.tcx.hir().body(body_id);
3183 let closure_expr = remove_blocks(&closure_body.value);
3185 if let hir::ExprKind::MethodCall(_, _, args) = &closure_expr.kind;
3187 if let hir::ExprKind::Path(qpath) = &args[0].kind;
3188 if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id);
3189 if closure_body.params[0].pat.hir_id == local_id;
3190 let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::<Box<[_]>>();
3191 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3193 let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap();
3194 deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3205 let current_method = if is_mut {
3206 ".as_mut().map(DerefMut::deref_mut)"
3208 ".as_ref().map(Deref::deref)"
3210 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3211 let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3212 let suggestion = format!("try using {} instead", method_hint);
3215 "called `{0}` (or with one of deref aliases) on an Option value. \
3216 This can be done more directly by calling `{1}` instead",
3217 current_method, hint
3221 OPTION_AS_REF_DEREF,
3226 Applicability::MachineApplicable,
3231 /// Given a `Result<T, E>` type, return its error type (`E`).
3232 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3234 ty::Adt(_, substs) if match_type(cx, ty, &paths::RESULT) => substs.types().nth(1),
3239 /// This checks whether a given type is known to implement Debug.
3240 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
3242 .get_diagnostic_item(sym::debug_trait)
3243 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3248 StartsWith(&'static str),
3252 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3253 (Convention::Eq("new"), &[SelfKind::No]),
3254 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3255 (Convention::StartsWith("from_"), &[SelfKind::No]),
3256 (Convention::StartsWith("into_"), &[SelfKind::Value]),
3257 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3258 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3259 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3263 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
3264 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
3265 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
3266 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
3267 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
3268 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
3269 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
3270 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
3271 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
3272 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
3273 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
3274 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
3275 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
3276 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
3277 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
3278 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
3279 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
3280 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
3281 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
3282 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
3283 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
3284 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
3285 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
3286 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
3287 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
3288 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
3289 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
3290 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
3291 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
3292 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
3293 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
3297 const PATTERN_METHODS: [(&str, usize); 17] = [
3305 ("split_terminator", 1),
3306 ("rsplit_terminator", 1),
3311 ("match_indices", 1),
3312 ("rmatch_indices", 1),
3313 ("trim_start_matches", 1),
3314 ("trim_end_matches", 1),
3317 #[derive(Clone, Copy, PartialEq, Debug)]
3326 fn matches<'a>(self, cx: &LateContext<'_, 'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3327 fn matches_value(parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3328 if ty == parent_ty {
3330 } else if ty.is_box() {
3331 ty.boxed_ty() == parent_ty
3332 } else if ty.is_rc() || ty.is_arc() {
3333 if let ty::Adt(_, substs) = ty.kind {
3334 substs.types().next().map_or(false, |t| t == parent_ty)
3344 cx: &LateContext<'_, 'a>,
3345 mutability: hir::Mutability,
3349 if let ty::Ref(_, t, m) = ty.kind {
3350 return m == mutability && t == parent_ty;
3353 let trait_path = match mutability {
3354 hir::Mutability::Not => &paths::ASREF_TRAIT,
3355 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3358 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3360 None => return false,
3362 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3366 Self::Value => matches_value(parent_ty, ty),
3367 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3368 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3369 Self::No => ty != parent_ty,
3374 fn description(self) -> &'static str {
3376 Self::Value => "self by value",
3377 Self::Ref => "self by reference",
3378 Self::RefMut => "self by mutable reference",
3379 Self::No => "no self",
3386 fn check(&self, other: &str) -> bool {
3388 Self::Eq(this) => this == other,
3389 Self::StartsWith(this) => other.starts_with(this) && this != other,
3394 impl fmt::Display for Convention {
3395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3397 Self::Eq(this) => this.fmt(f),
3398 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3403 #[derive(Clone, Copy)]
3412 fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FnRetTy<'_>) -> bool {
3413 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3415 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3416 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3417 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3418 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3419 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3425 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3426 if let hir::TyKind::Path(ref p) = ty.kind {
3427 match_qpath(p, &["bool"])
3433 // Returns `true` if `expr` contains a return expression
3434 fn contains_return(expr: &hir::Expr<'_>) -> bool {
3435 struct RetCallFinder {
3439 impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
3440 type Map = Map<'tcx>;
3442 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
3446 if let hir::ExprKind::Ret(..) = &expr.kind {
3449 intravisit::walk_expr(self, expr);
3453 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
3454 intravisit::NestedVisitorMap::None
3458 let mut visitor = RetCallFinder { found: false };
3459 visitor.visit_expr(expr);
3463 fn check_pointer_offset(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3466 if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.tables.expr_ty(&args[0]).kind;
3467 if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3470 span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3475 fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3476 let ty = cx.tables.expr_ty(&args[0]);
3478 if !match_type(cx, ty, &paths::FILE_TYPE) {
3484 let lint_unary: &str;
3485 let help_unary: &str;
3487 if let Some(parent) = get_parent_expr(cx, expr);
3488 if let hir::ExprKind::Unary(op, _) = parent.kind;
3489 if op == hir::UnOp::UnNot;
3502 let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3503 let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3504 span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, &help_msg);