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::hir::map::Map;
13 use rustc::lint::in_external_macro;
14 use rustc::ty::{self, Predicate, Ty};
16 use rustc_errors::Applicability;
18 use rustc_hir::intravisit::{self, Visitor};
19 use rustc_lint::{LateContext, LateLintPass, Lint, LintContext};
20 use rustc_session::{declare_lint_pass, declare_tool_lint};
21 use rustc_span::source_map::Span;
22 use rustc_span::symbol::{sym, Symbol, SymbolStr};
24 use crate::consts::{constant, Constant};
25 use crate::utils::usage::mutated_variables;
27 get_arg_name, get_parent_expr, get_trait_def_id, has_iter_method, implements_trait, in_macro, is_copy,
28 is_ctor_or_promotable_const_function, is_expn_of, is_type_diagnostic_item, iter_input_pats, last_path_segment,
29 match_def_path, match_qpath, match_trait_method, match_type, match_var, method_calls, method_chain_args, paths,
30 remove_blocks, return_ty, same_tys, single_segment_path, snippet, snippet_with_applicability,
31 snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_note, span_lint_and_sugg,
32 span_lint_and_then, sugg, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq,
35 declare_clippy_lint! {
36 /// **What it does:** Checks for `.unwrap()` calls on `Option`s.
38 /// **Why is this bad?** Usually it is better to handle the `None` case, or to
39 /// at least call `.expect(_)` with a more helpful message. Still, for a lot of
40 /// quick-and-dirty code, `unwrap` is a good choice, which is why this lint is
41 /// `Allow` by default.
43 /// **Known problems:** None.
47 /// Using unwrap on an `Option`:
50 /// let opt = Some(1);
57 /// let opt = Some(1);
58 /// opt.expect("more helpful message");
60 pub OPTION_UNWRAP_USED,
62 "using `Option.unwrap()`, which should at least get a better message using `expect()`"
65 declare_clippy_lint! {
66 /// **What it does:** Checks for `.unwrap()` calls on `Result`s.
68 /// **Why is this bad?** `result.unwrap()` will let the thread panic on `Err`
69 /// values. Normally, you want to implement more sophisticated error handling,
70 /// and propagate errors upwards with `?` operator.
72 /// Even if you want to panic on errors, not all `Error`s implement good
73 /// messages on display. Therefore, it may be beneficial to look at the places
74 /// where they may get displayed. Activate this lint to do just that.
76 /// **Known problems:** None.
79 /// Using unwrap on an `Result`:
82 /// let res: Result<usize, ()> = Ok(1);
89 /// let res: Result<usize, ()> = Ok(1);
90 /// res.expect("more helpful message");
92 pub RESULT_UNWRAP_USED,
94 "using `Result.unwrap()`, which might be better handled"
97 declare_clippy_lint! {
98 /// **What it does:** Checks for `.expect()` calls on `Option`s.
100 /// **Why is this bad?** Usually it is better to handle the `None` case. Still,
101 /// for a lot of quick-and-dirty code, `expect` is a good choice, which is why
102 /// this lint is `Allow` by default.
104 /// **Known problems:** None.
108 /// Using expect on an `Option`:
111 /// let opt = Some(1);
112 /// opt.expect("one");
118 /// let opt = Some(1);
121 pub OPTION_EXPECT_USED,
123 "using `Option.expect()`, which might be better handled"
126 declare_clippy_lint! {
127 /// **What it does:** Checks for `.expect()` calls on `Result`s.
129 /// **Why is this bad?** `result.expect()` will let the thread panic on `Err`
130 /// values. Normally, you want to implement more sophisticated error handling,
131 /// and propagate errors upwards with `?` operator.
133 /// **Known problems:** None.
136 /// Using expect on an `Result`:
139 /// let res: Result<usize, ()> = Ok(1);
140 /// res.expect("one");
146 /// let res: Result<usize, ()> = Ok(1);
148 /// # Ok::<(), ()>(())
150 pub RESULT_EXPECT_USED,
152 "using `Result.expect()`, which might be better handled"
155 declare_clippy_lint! {
156 /// **What it does:** Checks for methods that should live in a trait
157 /// implementation of a `std` trait (see [llogiq's blog
158 /// post](http://llogiq.github.io/2015/07/30/traits.html) for further
159 /// information) instead of an inherent implementation.
161 /// **Why is this bad?** Implementing the traits improve ergonomics for users of
162 /// the code, often with very little cost. Also people seeing a `mul(...)`
164 /// may expect `*` to work equally, so you should have good reason to disappoint
167 /// **Known problems:** None.
173 /// fn add(&self, other: &X) -> X {
179 pub SHOULD_IMPLEMENT_TRAIT,
181 "defining a method that should be implementing a std trait"
184 declare_clippy_lint! {
185 /// **What it does:** Checks for methods with certain name prefixes and which
186 /// doesn't match how self is taken. The actual rules are:
188 /// |Prefix |`self` taken |
189 /// |-------|----------------------|
190 /// |`as_` |`&self` or `&mut self`|
192 /// |`into_`|`self` |
193 /// |`is_` |`&self` or none |
194 /// |`to_` |`&self` |
196 /// **Why is this bad?** Consistency breeds readability. If you follow the
197 /// conventions, your users won't be surprised that they, e.g., need to supply a
198 /// mutable reference to a `as_..` function.
200 /// **Known problems:** None.
206 /// fn as_str(self) -> &'static str {
212 pub WRONG_SELF_CONVENTION,
214 "defining a method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
217 declare_clippy_lint! {
218 /// **What it does:** This is the same as
219 /// [`wrong_self_convention`](#wrong_self_convention), but for public items.
221 /// **Why is this bad?** See [`wrong_self_convention`](#wrong_self_convention).
223 /// **Known problems:** Actually *renaming* the function may break clients if
224 /// the function is part of the public interface. In that case, be mindful of
225 /// the stability guarantees you've given your users.
231 /// pub fn as_str(self) -> &'a str {
236 pub WRONG_PUB_SELF_CONVENTION,
238 "defining a public method named with an established prefix (like \"into_\") that takes `self` with the wrong convention"
241 declare_clippy_lint! {
242 /// **What it does:** Checks for usage of `ok().expect(..)`.
244 /// **Why is this bad?** Because you usually call `expect()` on the `Result`
245 /// directly to get a better error message.
247 /// **Known problems:** The error type needs to implement `Debug`
251 /// # let x = Ok::<_, ()>(());
252 /// x.ok().expect("why did I do this again?")
256 "using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
259 declare_clippy_lint! {
260 /// **What it does:** Checks for usage of `_.map(_).unwrap_or(_)`.
262 /// **Why is this bad?** Readability, this can be written more concisely as
263 /// `_.map_or(_, _)`.
265 /// **Known problems:** The order of the arguments is not in execution order
269 /// # let x = Some(1);
270 /// x.map(|a| a + 1).unwrap_or(0);
272 pub OPTION_MAP_UNWRAP_OR,
274 "using `Option.map(f).unwrap_or(a)`, which is more succinctly expressed as `map_or(a, f)`"
277 declare_clippy_lint! {
278 /// **What it does:** Checks for usage of `_.map(_).unwrap_or_else(_)`.
280 /// **Why is this bad?** Readability, this can be written more concisely as
281 /// `_.map_or_else(_, _)`.
283 /// **Known problems:** The order of the arguments is not in execution order.
287 /// # let x = Some(1);
288 /// # fn some_function() -> usize { 1 }
289 /// x.map(|a| a + 1).unwrap_or_else(some_function);
291 pub OPTION_MAP_UNWRAP_OR_ELSE,
293 "using `Option.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `map_or_else(g, f)`"
296 declare_clippy_lint! {
297 /// **What it does:** Checks for usage of `result.map(_).unwrap_or_else(_)`.
299 /// **Why is this bad?** Readability, this can be written more concisely as
300 /// `result.map_or_else(_, _)`.
302 /// **Known problems:** None.
306 /// # let x: Result<usize, ()> = Ok(1);
307 /// # fn some_function(foo: ()) -> usize { 1 }
308 /// x.map(|a| a + 1).unwrap_or_else(some_function);
310 pub RESULT_MAP_UNWRAP_OR_ELSE,
312 "using `Result.map(f).unwrap_or_else(g)`, which is more succinctly expressed as `.map_or_else(g, f)`"
315 declare_clippy_lint! {
316 /// **What it does:** Checks for usage of `_.map_or(None, _)`.
318 /// **Why is this bad?** Readability, this can be written more concisely as
321 /// **Known problems:** The order of the arguments is not in execution order.
325 /// # let opt = Some(1);
326 /// opt.map_or(None, |a| Some(a + 1))
329 pub OPTION_MAP_OR_NONE,
331 "using `Option.map_or(None, f)`, which is more succinctly expressed as `and_then(f)`"
334 declare_clippy_lint! {
335 /// **What it does:** Checks for usage of `_.and_then(|x| Some(y))`.
337 /// **Why is this bad?** Readability, this can be written more concisely as
340 /// **Known problems:** None
345 /// let x = Some("foo");
346 /// let _ = x.and_then(|s| Some(s.len()));
349 /// The correct use would be:
352 /// let x = Some("foo");
353 /// let _ = x.map(|s| s.len());
355 pub OPTION_AND_THEN_SOME,
357 "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`"
360 declare_clippy_lint! {
361 /// **What it does:** Checks for usage of `_.filter(_).next()`.
363 /// **Why is this bad?** Readability, this can be written more concisely as
366 /// **Known problems:** None.
370 /// # let vec = vec![1];
371 /// vec.iter().filter(|x| **x == 0).next();
373 /// Could be written as
375 /// # let vec = vec![1];
376 /// vec.iter().find(|x| **x == 0);
380 "using `filter(p).next()`, which is more succinctly expressed as `.find(p)`"
383 declare_clippy_lint! {
384 /// **What it does:** Checks for usage of `_.skip_while(condition).next()`.
386 /// **Why is this bad?** Readability, this can be written more concisely as
387 /// `_.find(!condition)`.
389 /// **Known problems:** None.
393 /// # let vec = vec![1];
394 /// vec.iter().skip_while(|x| **x == 0).next();
396 /// Could be written as
398 /// # let vec = vec![1];
399 /// vec.iter().find(|x| **x != 0);
403 "using `skip_while(p).next()`, which is more succinctly expressed as `.find(!p)`"
406 declare_clippy_lint! {
407 /// **What it does:** Checks for usage of `_.map(_).flatten(_)`,
409 /// **Why is this bad?** Readability, this can be written more concisely as a
410 /// single method call.
412 /// **Known problems:**
416 /// let vec = vec![vec![1]];
417 /// vec.iter().map(|x| x.iter()).flatten();
421 "using combinations of `flatten` and `map` which can usually be written as a single method call"
424 declare_clippy_lint! {
425 /// **What it does:** Checks for usage of `_.filter(_).map(_)`,
426 /// `_.filter(_).flat_map(_)`, `_.filter_map(_).flat_map(_)` and similar.
428 /// **Why is this bad?** Readability, this can be written more concisely as a
429 /// single method call.
431 /// **Known problems:** Often requires a condition + Option/Iterator creation
432 /// inside the closure.
436 /// let vec = vec![1];
437 /// vec.iter().filter(|x| **x == 0).map(|x| *x * 2);
441 "using combinations of `filter`, `map`, `filter_map` and `flat_map` which can usually be written as a single method call"
444 declare_clippy_lint! {
445 /// **What it does:** Checks for usage of `_.filter_map(_).next()`.
447 /// **Why is this bad?** Readability, this can be written more concisely as a
448 /// single method call.
450 /// **Known problems:** None
454 /// (0..3).filter_map(|x| if x == 2 { Some(x) } else { None }).next();
456 /// Can be written as
459 /// (0..3).find_map(|x| if x == 2 { Some(x) } else { None });
463 "using combination of `filter_map` and `next` which can usually be written as a single method call"
466 declare_clippy_lint! {
467 /// **What it does:** Checks for usage of `flat_map(|x| x)`.
469 /// **Why is this bad?** Readability, this can be written more concisely by using `flatten`.
471 /// **Known problems:** None
475 /// # let iter = vec![vec![0]].into_iter();
476 /// iter.flat_map(|x| x);
478 /// Can be written as
480 /// # let iter = vec![vec![0]].into_iter();
483 pub FLAT_MAP_IDENTITY,
485 "call to `flat_map` where `flatten` is sufficient"
488 declare_clippy_lint! {
489 /// **What it does:** Checks for usage of `_.find(_).map(_)`.
491 /// **Why is this bad?** Readability, this can be written more concisely as a
492 /// single method call.
494 /// **Known problems:** Often requires a condition + Option/Iterator creation
495 /// inside the closure.
499 /// (0..3).find(|x| *x == 2).map(|x| x * 2);
501 /// Can be written as
503 /// (0..3).find_map(|x| if x == 2 { Some(x * 2) } else { None });
507 "using a combination of `find` and `map` can usually be written as a single method call"
510 declare_clippy_lint! {
511 /// **What it does:** Checks for an iterator search (such as `find()`,
512 /// `position()`, or `rposition()`) followed by a call to `is_some()`.
514 /// **Why is this bad?** Readability, this can be written more concisely as
517 /// **Known problems:** None.
521 /// # let vec = vec![1];
522 /// vec.iter().find(|x| **x == 0).is_some();
524 /// Could be written as
526 /// # let vec = vec![1];
527 /// vec.iter().any(|x| *x == 0);
531 "using an iterator search followed by `is_some()`, which is more succinctly expressed as a call to `any()`"
534 declare_clippy_lint! {
535 /// **What it does:** Checks for usage of `.chars().next()` on a `str` to check
536 /// if it starts with a given char.
538 /// **Why is this bad?** Readability, this can be written more concisely as
539 /// `_.starts_with(_)`.
541 /// **Known problems:** None.
545 /// let name = "foo";
546 /// if name.chars().next() == Some('_') {};
548 /// Could be written as
550 /// let name = "foo";
551 /// if name.starts_with('_') {};
555 "using `.chars().next()` to check if a string starts with a char"
558 declare_clippy_lint! {
559 /// **What it does:** Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
560 /// etc., and suggests to use `or_else`, `unwrap_or_else`, etc., or
561 /// `unwrap_or_default` instead.
563 /// **Why is this bad?** The function will always be called and potentially
564 /// allocate an object acting as the default.
566 /// **Known problems:** If the function has side-effects, not calling it will
567 /// change the semantic of the program, but you shouldn't rely on that anyway.
571 /// # let foo = Some(String::new());
572 /// foo.unwrap_or(String::new());
574 /// this can instead be written:
576 /// # let foo = Some(String::new());
577 /// foo.unwrap_or_else(String::new);
581 /// # let foo = Some(String::new());
582 /// foo.unwrap_or_default();
586 "using any `*or` method with a function call, which suggests `*or_else`"
589 declare_clippy_lint! {
590 /// **What it does:** Checks for calls to `.expect(&format!(...))`, `.expect(foo(..))`,
591 /// etc., and suggests to use `unwrap_or_else` instead
593 /// **Why is this bad?** The function will always be called.
595 /// **Known problems:** If the function has side-effects, not calling it will
596 /// change the semantics of the program, but you shouldn't rely on that anyway.
600 /// # let foo = Some(String::new());
601 /// # let err_code = "418";
602 /// # let err_msg = "I'm a teapot";
603 /// foo.expect(&format!("Err {}: {}", err_code, err_msg));
607 /// # let foo = Some(String::new());
608 /// # let err_code = "418";
609 /// # let err_msg = "I'm a teapot";
610 /// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str());
612 /// this can instead be written:
614 /// # let foo = Some(String::new());
615 /// # let err_code = "418";
616 /// # let err_msg = "I'm a teapot";
617 /// foo.unwrap_or_else(|| panic!("Err {}: {}", err_code, err_msg));
621 "using any `expect` method with a function call"
624 declare_clippy_lint! {
625 /// **What it does:** Checks for usage of `.clone()` on a `Copy` type.
627 /// **Why is this bad?** The only reason `Copy` types implement `Clone` is for
628 /// generics, not for using the `clone` method on a concrete type.
630 /// **Known problems:** None.
638 "using `clone` on a `Copy` type"
641 declare_clippy_lint! {
642 /// **What it does:** Checks for usage of `.clone()` on a ref-counted pointer,
643 /// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
644 /// function syntax instead (e.g., `Rc::clone(foo)`).
646 /// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
647 /// can obscure the fact that only the pointer is being cloned, not the underlying
652 /// # use std::rc::Rc;
653 /// let x = Rc::new(1);
656 pub CLONE_ON_REF_PTR,
658 "using 'clone' on a ref-counted pointer"
661 declare_clippy_lint! {
662 /// **What it does:** Checks for usage of `.clone()` on an `&&T`.
664 /// **Why is this bad?** Cloning an `&&T` copies the inner `&T`, instead of
665 /// cloning the underlying `T`.
667 /// **Known problems:** None.
674 /// let z = y.clone();
675 /// println!("{:p} {:p}", *y, z); // prints out the same pointer
678 pub CLONE_DOUBLE_REF,
680 "using `clone` on `&&T`"
683 declare_clippy_lint! {
684 /// **What it does:** Checks for usage of `.to_string()` on an `&&T` where
685 /// `T` implements `ToString` directly (like `&&str` or `&&String`).
687 /// **Why is this bad?** This bypasses the specialized implementation of
688 /// `ToString` and instead goes through the more expensive string formatting
691 /// **Known problems:** None.
695 /// // Generic implementation for `T: Display` is used (slow)
696 /// ["foo", "bar"].iter().map(|s| s.to_string());
698 /// // OK, the specialized impl is used
699 /// ["foo", "bar"].iter().map(|&s| s.to_string());
701 pub INEFFICIENT_TO_STRING,
703 "using `to_string` on `&&T` where `T: ToString`"
706 declare_clippy_lint! {
707 /// **What it does:** Checks for `new` not returning `Self`.
709 /// **Why is this bad?** As a convention, `new` methods are used to make a new
710 /// instance of a type.
712 /// **Known problems:** None.
717 /// # struct NotAFoo;
719 /// fn new() -> NotAFoo {
726 "not returning `Self` in a `new` method"
729 declare_clippy_lint! {
730 /// **What it does:** Checks for string methods that receive a single-character
731 /// `str` as an argument, e.g., `_.split("x")`.
733 /// **Why is this bad?** Performing these methods using a `char` is faster than
736 /// **Known problems:** Does not catch multi-byte unicode characters.
739 /// `_.split("x")` could be `_.split('x')`
740 pub SINGLE_CHAR_PATTERN,
742 "using a single-character str where a char could be used, e.g., `_.split(\"x\")`"
745 declare_clippy_lint! {
746 /// **What it does:** Checks for getting the inner pointer of a temporary
749 /// **Why is this bad?** The inner pointer of a `CString` is only valid as long
750 /// as the `CString` is alive.
752 /// **Known problems:** None.
756 /// # use std::ffi::CString;
757 /// # fn call_some_ffi_func(_: *const i8) {}
759 /// let c_str = CString::new("foo").unwrap().as_ptr();
761 /// call_some_ffi_func(c_str);
764 /// Here `c_str` point to a freed address. The correct use would be:
766 /// # use std::ffi::CString;
767 /// # fn call_some_ffi_func(_: *const i8) {}
769 /// let c_str = CString::new("foo").unwrap();
771 /// call_some_ffi_func(c_str.as_ptr());
774 pub TEMPORARY_CSTRING_AS_PTR,
776 "getting the inner pointer of a temporary `CString`"
779 declare_clippy_lint! {
780 /// **What it does:** Checks for calling `.step_by(0)` on iterators which panics.
782 /// **Why is this bad?** This very much looks like an oversight. Use `panic!()` instead if you
783 /// actually intend to panic.
785 /// **Known problems:** None.
788 /// ```rust,should_panic
789 /// for x in (0..100).step_by(0) {
793 pub ITERATOR_STEP_BY_ZERO,
795 "using `Iterator::step_by(0)`, which will panic at runtime"
798 declare_clippy_lint! {
799 /// **What it does:** Checks for the use of `iter.nth(0)`.
801 /// **Why is this bad?** `iter.next()` is equivalent to
802 /// `iter.nth(0)`, as they both consume the next element,
803 /// but is more readable.
805 /// **Known problems:** None.
810 /// # use std::collections::HashSet;
812 /// # let mut s = HashSet::new();
814 /// let x = s.iter().nth(0);
817 /// # let mut s = HashSet::new();
819 /// let x = s.iter().next();
823 "replace `iter.nth(0)` with `iter.next()`"
826 declare_clippy_lint! {
827 /// **What it does:** Checks for use of `.iter().nth()` (and the related
828 /// `.iter_mut().nth()`) on standard library types with O(1) element access.
830 /// **Why is this bad?** `.get()` and `.get_mut()` are more efficient and more
833 /// **Known problems:** None.
837 /// let some_vec = vec![0, 1, 2, 3];
838 /// let bad_vec = some_vec.iter().nth(3);
839 /// let bad_slice = &some_vec[..].iter().nth(3);
841 /// The correct use would be:
843 /// let some_vec = vec![0, 1, 2, 3];
844 /// let bad_vec = some_vec.get(3);
845 /// let bad_slice = &some_vec[..].get(3);
849 "using `.iter().nth()` on a standard library type with O(1) element access"
852 declare_clippy_lint! {
853 /// **What it does:** Checks for use of `.skip(x).next()` on iterators.
855 /// **Why is this bad?** `.nth(x)` is cleaner
857 /// **Known problems:** None.
861 /// let some_vec = vec![0, 1, 2, 3];
862 /// let bad_vec = some_vec.iter().skip(3).next();
863 /// let bad_slice = &some_vec[..].iter().skip(3).next();
865 /// The correct use would be:
867 /// let some_vec = vec![0, 1, 2, 3];
868 /// let bad_vec = some_vec.iter().nth(3);
869 /// let bad_slice = &some_vec[..].iter().nth(3);
873 "using `.skip(x).next()` on an iterator"
876 declare_clippy_lint! {
877 /// **What it does:** Checks for use of `.get().unwrap()` (or
878 /// `.get_mut().unwrap`) on a standard library type which implements `Index`
880 /// **Why is this bad?** Using the Index trait (`[]`) is more clear and more
883 /// **Known problems:** Not a replacement for error handling: Using either
884 /// `.unwrap()` or the Index trait (`[]`) carries the risk of causing a `panic`
885 /// if the value being accessed is `None`. If the use of `.get().unwrap()` is a
886 /// temporary placeholder for dealing with the `Option` type, then this does
887 /// not mitigate the need for error handling. If there is a chance that `.get()`
888 /// will be `None` in your program, then it is advisable that the `None` case
889 /// is handled in a future refactor instead of using `.unwrap()` or the Index
894 /// let mut some_vec = vec![0, 1, 2, 3];
895 /// let last = some_vec.get(3).unwrap();
896 /// *some_vec.get_mut(0).unwrap() = 1;
898 /// The correct use would be:
900 /// let mut some_vec = vec![0, 1, 2, 3];
901 /// let last = some_vec[3];
906 "using `.get().unwrap()` or `.get_mut().unwrap()` when using `[]` would work instead"
909 declare_clippy_lint! {
910 /// **What it does:** Checks for the use of `.extend(s.chars())` where s is a
911 /// `&str` or `String`.
913 /// **Why is this bad?** `.push_str(s)` is clearer
915 /// **Known problems:** None.
920 /// let def = String::from("def");
921 /// let mut s = String::new();
922 /// s.extend(abc.chars());
923 /// s.extend(def.chars());
925 /// The correct use would be:
928 /// let def = String::from("def");
929 /// let mut s = String::new();
931 /// s.push_str(&def);
933 pub STRING_EXTEND_CHARS,
935 "using `x.extend(s.chars())` where s is a `&str` or `String`"
938 declare_clippy_lint! {
939 /// **What it does:** Checks for the use of `.cloned().collect()` on slice to
942 /// **Why is this bad?** `.to_vec()` is clearer
944 /// **Known problems:** None.
948 /// let s = [1, 2, 3, 4, 5];
949 /// let s2: Vec<isize> = s[..].iter().cloned().collect();
951 /// The better use would be:
953 /// let s = [1, 2, 3, 4, 5];
954 /// let s2: Vec<isize> = s.to_vec();
956 pub ITER_CLONED_COLLECT,
958 "using `.cloned().collect()` on slice to create a `Vec`"
961 declare_clippy_lint! {
962 /// **What it does:** Checks for usage of `.chars().last()` or
963 /// `.chars().next_back()` on a `str` to check if it ends with a given char.
965 /// **Why is this bad?** Readability, this can be written more concisely as
966 /// `_.ends_with(_)`.
968 /// **Known problems:** None.
972 /// # let name = "_";
973 /// name.chars().last() == Some('_') || name.chars().next_back() == Some('-')
978 "using `.chars().last()` or `.chars().next_back()` to check if a string ends with a char"
981 declare_clippy_lint! {
982 /// **What it does:** Checks for usage of `.as_ref()` or `.as_mut()` where the
983 /// types before and after the call are the same.
985 /// **Why is this bad?** The call is unnecessary.
987 /// **Known problems:** None.
991 /// # fn do_stuff(x: &[i32]) {}
992 /// let x: &[i32] = &[1, 2, 3, 4, 5];
993 /// do_stuff(x.as_ref());
995 /// The correct use would be:
997 /// # fn do_stuff(x: &[i32]) {}
998 /// let x: &[i32] = &[1, 2, 3, 4, 5];
1003 "using `as_ref` where the types before and after the call are the same"
1006 declare_clippy_lint! {
1007 /// **What it does:** Checks for using `fold` when a more succinct alternative exists.
1008 /// Specifically, this checks for `fold`s which could be replaced by `any`, `all`,
1009 /// `sum` or `product`.
1011 /// **Why is this bad?** Readability.
1013 /// **Known problems:** False positive in pattern guards. Will be resolved once
1014 /// non-lexical lifetimes are stable.
1018 /// let _ = (0..3).fold(false, |acc, x| acc || x > 2);
1020 /// This could be written as:
1022 /// let _ = (0..3).any(|x| x > 2);
1024 pub UNNECESSARY_FOLD,
1026 "using `fold` when a more succinct alternative exists"
1029 declare_clippy_lint! {
1030 /// **What it does:** Checks for `filter_map` calls which could be replaced by `filter` or `map`.
1031 /// More specifically it checks if the closure provided is only performing one of the
1032 /// filter or map operations and suggests the appropriate option.
1034 /// **Why is this bad?** Complexity. The intent is also clearer if only a single
1035 /// operation is being performed.
1037 /// **Known problems:** None
1041 /// let _ = (0..3).filter_map(|x| if x > 2 { Some(x) } else { None });
1043 /// As there is no transformation of the argument this could be written as:
1045 /// let _ = (0..3).filter(|&x| x > 2);
1049 /// let _ = (0..4).filter_map(|x| Some(x + 1));
1051 /// As there is no conditional check on the argument this could be written as:
1053 /// let _ = (0..4).map(|x| x + 1);
1055 pub UNNECESSARY_FILTER_MAP,
1057 "using `filter_map` when a more succinct alternative exists"
1060 declare_clippy_lint! {
1061 /// **What it does:** Checks for `into_iter` calls on references which should be replaced by `iter`
1064 /// **Why is this bad?** Readability. Calling `into_iter` on a reference will not move out its
1065 /// content into the resulting iterator, which is confusing. It is better just call `iter` or
1066 /// `iter_mut` directly.
1068 /// **Known problems:** None
1073 /// let _ = (&vec![3, 4, 5]).into_iter();
1075 pub INTO_ITER_ON_REF,
1077 "using `.into_iter()` on a reference"
1080 declare_clippy_lint! {
1081 /// **What it does:** Checks for calls to `map` followed by a `count`.
1083 /// **Why is this bad?** It looks suspicious. Maybe `map` was confused with `filter`.
1084 /// If the `map` call is intentional, this should be rewritten. Or, if you intend to
1085 /// drive the iterator to completion, you can just use `for_each` instead.
1087 /// **Known problems:** None
1092 /// let _ = (0..3).map(|x| x + 2).count();
1096 "suspicious usage of map"
1099 declare_clippy_lint! {
1100 /// **What it does:** Checks for `MaybeUninit::uninit().assume_init()`.
1102 /// **Why is this bad?** For most types, this is undefined behavior.
1104 /// **Known problems:** For now, we accept empty tuples and tuples / arrays
1105 /// of `MaybeUninit`. There may be other types that allow uninitialized
1106 /// data, but those are not yet rigorously defined.
1111 /// // Beware the UB
1112 /// use std::mem::MaybeUninit;
1114 /// let _: usize = unsafe { MaybeUninit::uninit().assume_init() };
1117 /// Note that the following is OK:
1120 /// use std::mem::MaybeUninit;
1122 /// let _: [MaybeUninit<bool>; 5] = unsafe {
1123 /// MaybeUninit::uninit().assume_init()
1126 pub UNINIT_ASSUMED_INIT,
1128 "`MaybeUninit::uninit().assume_init()`"
1131 declare_clippy_lint! {
1132 /// **What it does:** Checks for `.checked_add/sub(x).unwrap_or(MAX/MIN)`.
1134 /// **Why is this bad?** These can be written simply with `saturating_add/sub` methods.
1139 /// # let y: u32 = 0;
1140 /// # let x: u32 = 100;
1141 /// let add = x.checked_add(y).unwrap_or(u32::max_value());
1142 /// let sub = x.checked_sub(y).unwrap_or(u32::min_value());
1145 /// can be written using dedicated methods for saturating addition/subtraction as:
1148 /// # let y: u32 = 0;
1149 /// # let x: u32 = 100;
1150 /// let add = x.saturating_add(y);
1151 /// let sub = x.saturating_sub(y);
1153 pub MANUAL_SATURATING_ARITHMETIC,
1155 "`.chcked_add/sub(x).unwrap_or(MAX/MIN)`"
1158 declare_clippy_lint! {
1159 /// **What it does:** Checks for `offset(_)`, `wrapping_`{`add`, `sub`}, etc. on raw pointers to
1160 /// zero-sized types
1162 /// **Why is this bad?** This is a no-op, and likely unintended
1164 /// **Known problems:** None
1168 /// unsafe { (&() as *const ()).offset(1) };
1172 "Check for offset calculations on raw pointers to zero-sized types"
1175 declare_clippy_lint! {
1176 /// **What it does:** Checks for `FileType::is_file()`.
1178 /// **Why is this bad?** When people testing a file type with `FileType::is_file`
1179 /// they are testing whether a path is something they can get bytes from. But
1180 /// `is_file` doesn't cover special file types in unix-like systems, and doesn't cover
1181 /// symlink in windows. Using `!FileType::is_dir()` is a better way to that intention.
1187 /// let metadata = std::fs::metadata("foo.txt")?;
1188 /// let filetype = metadata.file_type();
1190 /// if filetype.is_file() {
1193 /// # Ok::<_, std::io::Error>(())
1197 /// should be written as:
1201 /// let metadata = std::fs::metadata("foo.txt")?;
1202 /// let filetype = metadata.file_type();
1204 /// if !filetype.is_dir() {
1207 /// # Ok::<_, std::io::Error>(())
1210 pub FILETYPE_IS_FILE,
1212 "`FileType::is_file` is not recommended to test for readable file type"
1215 declare_clippy_lint! {
1216 /// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1218 /// **Why is this bad?** Readability, this can be written more concisely as a
1219 /// single method call.
1221 /// **Known problems:** None.
1225 /// # let opt = Some("".to_string());
1226 /// opt.as_ref().map(String::as_str)
1229 /// Can be written as
1231 /// # let opt = Some("".to_string());
1235 pub OPTION_AS_REF_DEREF,
1237 "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1240 declare_lint_pass!(Methods => [
1245 SHOULD_IMPLEMENT_TRAIT,
1246 WRONG_SELF_CONVENTION,
1247 WRONG_PUB_SELF_CONVENTION,
1249 OPTION_MAP_UNWRAP_OR,
1250 OPTION_MAP_UNWRAP_OR_ELSE,
1251 RESULT_MAP_UNWRAP_OR_ELSE,
1253 OPTION_AND_THEN_SOME,
1261 INEFFICIENT_TO_STRING,
1263 SINGLE_CHAR_PATTERN,
1265 TEMPORARY_CSTRING_AS_PTR,
1273 ITERATOR_STEP_BY_ZERO,
1278 STRING_EXTEND_CHARS,
1279 ITER_CLONED_COLLECT,
1282 UNNECESSARY_FILTER_MAP,
1285 UNINIT_ASSUMED_INIT,
1286 MANUAL_SATURATING_ARITHMETIC,
1289 OPTION_AS_REF_DEREF,
1292 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
1293 #[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
1294 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
1295 if in_macro(expr.span) {
1299 let (method_names, arg_lists, method_spans) = method_calls(expr, 2);
1300 let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
1301 let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
1303 match method_names.as_slice() {
1304 ["unwrap", "get"] => lint_get_unwrap(cx, expr, arg_lists[1], false),
1305 ["unwrap", "get_mut"] => lint_get_unwrap(cx, expr, arg_lists[1], true),
1306 ["unwrap", ..] => lint_unwrap(cx, expr, arg_lists[0]),
1307 ["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
1308 ["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
1309 ["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1310 ["unwrap_or_else", "map"] => lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]),
1311 ["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
1312 ["and_then", ..] => lint_option_and_then_some(cx, expr, arg_lists[0]),
1313 ["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
1314 ["next", "skip_while"] => lint_skip_while_next(cx, expr, arg_lists[1]),
1315 ["map", "filter"] => lint_filter_map(cx, expr, arg_lists[1], arg_lists[0]),
1316 ["map", "filter_map"] => lint_filter_map_map(cx, expr, arg_lists[1], arg_lists[0]),
1317 ["next", "filter_map"] => lint_filter_map_next(cx, expr, arg_lists[1]),
1318 ["map", "find"] => lint_find_map(cx, expr, arg_lists[1], arg_lists[0]),
1319 ["flat_map", "filter"] => lint_filter_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1320 ["flat_map", "filter_map"] => lint_filter_map_flat_map(cx, expr, arg_lists[1], arg_lists[0]),
1321 ["flat_map", ..] => lint_flat_map_identity(cx, expr, arg_lists[0], method_spans[0]),
1322 ["flatten", "map"] => lint_map_flatten(cx, expr, arg_lists[1]),
1323 ["is_some", "find"] => lint_search_is_some(cx, expr, "find", arg_lists[1], arg_lists[0], method_spans[1]),
1324 ["is_some", "position"] => {
1325 lint_search_is_some(cx, expr, "position", arg_lists[1], arg_lists[0], method_spans[1])
1327 ["is_some", "rposition"] => {
1328 lint_search_is_some(cx, expr, "rposition", arg_lists[1], arg_lists[0], method_spans[1])
1330 ["extend", ..] => lint_extend(cx, expr, arg_lists[0]),
1331 ["as_ptr", "unwrap"] | ["as_ptr", "expect"] => {
1332 lint_cstring_as_ptr(cx, expr, &arg_lists[1][0], &arg_lists[0][0])
1334 ["nth", "iter"] => lint_iter_nth(cx, expr, &arg_lists, false),
1335 ["nth", "iter_mut"] => lint_iter_nth(cx, expr, &arg_lists, true),
1336 ["nth", ..] => lint_iter_nth_zero(cx, expr, arg_lists[0]),
1337 ["step_by", ..] => lint_step_by(cx, expr, arg_lists[0]),
1338 ["next", "skip"] => lint_iter_skip_next(cx, expr),
1339 ["collect", "cloned"] => lint_iter_cloned_collect(cx, expr, arg_lists[1]),
1340 ["as_ref"] => lint_asref(cx, expr, "as_ref", arg_lists[0]),
1341 ["as_mut"] => lint_asref(cx, expr, "as_mut", arg_lists[0]),
1342 ["fold", ..] => lint_unnecessary_fold(cx, expr, arg_lists[0], method_spans[0]),
1343 ["filter_map", ..] => unnecessary_filter_map::lint(cx, expr, arg_lists[0]),
1344 ["count", "map"] => lint_suspicious_map(cx, expr),
1345 ["assume_init"] => lint_maybe_uninit(cx, &arg_lists[0][0], expr),
1346 ["unwrap_or", arith @ "checked_add"]
1347 | ["unwrap_or", arith @ "checked_sub"]
1348 | ["unwrap_or", arith @ "checked_mul"] => {
1349 manual_saturating_arithmetic::lint(cx, expr, &arg_lists, &arith["checked_".len()..])
1351 ["add"] | ["offset"] | ["sub"] | ["wrapping_offset"] | ["wrapping_add"] | ["wrapping_sub"] => {
1352 check_pointer_offset(cx, expr, arg_lists[0])
1354 ["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1355 ["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
1356 ["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
1361 hir::ExprKind::MethodCall(ref method_call, ref method_span, ref args) => {
1362 lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1363 lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args);
1365 let self_ty = cx.tables.expr_ty_adjusted(&args[0]);
1366 if args.len() == 1 && method_call.ident.name == sym!(clone) {
1367 lint_clone_on_copy(cx, expr, &args[0], self_ty);
1368 lint_clone_on_ref_ptr(cx, expr, &args[0]);
1370 if args.len() == 1 && method_call.ident.name == sym!(to_string) {
1371 inefficient_to_string::lint(cx, expr, &args[0], self_ty);
1374 match self_ty.kind {
1375 ty::Ref(_, ty, _) if ty.kind == ty::Str => {
1376 for &(method, pos) in &PATTERN_METHODS {
1377 if method_call.ident.name.as_str() == method && args.len() > pos {
1378 lint_single_char_pattern(cx, expr, &args[pos]);
1382 ty::Ref(..) if method_call.ident.name == sym!(into_iter) => {
1383 lint_into_iter(cx, expr, self_ty, *method_span);
1388 hir::ExprKind::Binary(op, ref lhs, ref rhs)
1389 if op.node == hir::BinOpKind::Eq || op.node == hir::BinOpKind::Ne =>
1391 let mut info = BinaryExprInfo {
1395 eq: op.node == hir::BinOpKind::Eq,
1397 lint_binary_expr_with_method_call(cx, &mut info);
1403 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
1404 if in_external_macro(cx.sess(), impl_item.span) {
1407 let name = impl_item.ident.name.as_str();
1408 let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id);
1409 let item = cx.tcx.hir().expect_item(parent);
1410 let def_id = cx.tcx.hir().local_def_id(item.hir_id);
1411 let ty = cx.tcx.type_of(def_id);
1413 if let hir::ImplItemKind::Method(ref sig, id) = impl_item.kind;
1414 if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir().body(id)).next();
1415 if let hir::ItemKind::Impl{ of_trait: None, .. } = item.kind;
1417 let method_def_id = cx.tcx.hir().local_def_id(impl_item.hir_id);
1418 let method_sig = cx.tcx.fn_sig(method_def_id);
1419 let method_sig = cx.tcx.erase_late_bound_regions(&method_sig);
1421 let first_arg_ty = &method_sig.inputs().iter().next();
1423 // check conventions w.r.t. conversion method names and predicates
1424 if let Some(first_arg_ty) = first_arg_ty;
1427 if cx.access_levels.is_exported(impl_item.hir_id) {
1428 // check missing trait implementations
1429 for &(method_name, n_args, self_kind, out_type, trait_name) in &TRAIT_METHODS {
1430 if name == method_name &&
1431 sig.decl.inputs.len() == n_args &&
1432 out_type.matches(cx, &sig.decl.output) &&
1433 self_kind.matches(cx, ty, first_arg_ty) {
1434 span_lint(cx, SHOULD_IMPLEMENT_TRAIT, impl_item.span, &format!(
1435 "defining a method called `{}` on this type; consider implementing \
1436 the `{}` trait or choosing a less ambiguous name", name, trait_name));
1441 if let Some((ref conv, self_kinds)) = &CONVENTIONS
1443 .find(|(ref conv, _)| conv.check(&name))
1445 if !self_kinds.iter().any(|k| k.matches(cx, ty, first_arg_ty)) {
1446 let lint = if item.vis.node.is_pub() {
1447 WRONG_PUB_SELF_CONVENTION
1449 WRONG_SELF_CONVENTION
1457 "methods called `{}` usually take {}; consider choosing a less \
1462 .map(|k| k.description())
1463 .collect::<Vec<_>>()
1472 if let hir::ImplItemKind::Method(_, _) = impl_item.kind {
1473 let ret_ty = return_ty(cx, impl_item.hir_id);
1475 // walk the return type and check for Self (this does not check associated types)
1476 if ret_ty.walk().any(|inner_type| same_tys(cx, ty, inner_type)) {
1480 // if return type is impl trait, check the associated types
1481 if let ty::Opaque(def_id, _) = ret_ty.kind {
1482 // one of the associated types must be Self
1483 for predicate in cx.tcx.predicates_of(def_id).predicates {
1485 (Predicate::Projection(poly_projection_predicate), _) => {
1486 let binder = poly_projection_predicate.ty();
1487 let associated_type = binder.skip_binder();
1489 // walk the associated type and check for Self
1490 for inner_type in associated_type.walk() {
1491 if same_tys(cx, ty, inner_type) {
1501 if name == "new" && !same_tys(cx, ret_ty, ty) {
1506 "methods called `new` usually return `Self`",
1513 /// Checks for the `OR_FUN_CALL` lint.
1514 #[allow(clippy::too_many_lines)]
1515 fn lint_or_fun_call<'a, 'tcx>(
1516 cx: &LateContext<'a, 'tcx>,
1517 expr: &hir::Expr<'_>,
1520 args: &'tcx [hir::Expr<'_>],
1522 // Searches an expression for method calls or function calls that aren't ctors
1523 struct FunCallFinder<'a, 'tcx> {
1524 cx: &'a LateContext<'a, 'tcx>,
1528 impl<'a, 'tcx> intravisit::Visitor<'tcx> for FunCallFinder<'a, 'tcx> {
1529 type Map = Map<'tcx>;
1531 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
1532 let call_found = match &expr.kind {
1533 // ignore enum and struct constructors
1534 hir::ExprKind::Call(..) => !is_ctor_or_promotable_const_function(self.cx, expr),
1535 hir::ExprKind::MethodCall(..) => true,
1544 intravisit::walk_expr(self, expr);
1548 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
1549 intravisit::NestedVisitorMap::None
1553 /// Checks for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
1554 fn check_unwrap_or_default(
1555 cx: &LateContext<'_, '_>,
1557 fun: &hir::Expr<'_>,
1558 self_expr: &hir::Expr<'_>,
1559 arg: &hir::Expr<'_>,
1565 if name == "unwrap_or";
1566 if let hir::ExprKind::Path(ref qpath) = fun.kind;
1567 let path = &*last_path_segment(qpath).ident.as_str();
1568 if ["default", "new"].contains(&path);
1569 let arg_ty = cx.tables.expr_ty(arg);
1570 if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT);
1571 if implements_trait(cx, arg_ty, default_trait_id, &[]);
1574 let mut applicability = Applicability::MachineApplicable;
1579 &format!("use of `{}` followed by a call to `{}`", name, path),
1582 "{}.unwrap_or_default()",
1583 snippet_with_applicability(cx, self_expr.span, "_", &mut applicability)
1595 /// Checks for `*or(foo())`.
1596 #[allow(clippy::too_many_arguments)]
1597 fn check_general_case<'a, 'tcx>(
1598 cx: &LateContext<'a, 'tcx>,
1602 self_expr: &hir::Expr<'_>,
1603 arg: &'tcx hir::Expr<'_>,
1607 // (path, fn_has_argument, methods, suffix)
1608 let know_types: &[(&[_], _, &[_], _)] = &[
1609 (&paths::BTREEMAP_ENTRY, false, &["or_insert"], "with"),
1610 (&paths::HASHMAP_ENTRY, false, &["or_insert"], "with"),
1611 (&paths::OPTION, false, &["map_or", "ok_or", "or", "unwrap_or"], "else"),
1612 (&paths::RESULT, true, &["or", "unwrap_or"], "else"),
1616 if know_types.iter().any(|k| k.2.contains(&name));
1618 let mut finder = FunCallFinder { cx: &cx, found: false };
1619 if { finder.visit_expr(&arg); finder.found };
1620 if !contains_return(&arg);
1622 let self_ty = cx.tables.expr_ty(self_expr);
1624 if let Some(&(_, fn_has_arguments, poss, suffix)) =
1625 know_types.iter().find(|&&i| match_type(cx, self_ty, i.0));
1627 if poss.contains(&name);
1630 let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
1631 (true, _) => format!("|_| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1632 (false, false) => format!("|| {}", snippet_with_macro_callsite(cx, arg.span, "..")).into(),
1633 (false, true) => snippet_with_macro_callsite(cx, fun_span, ".."),
1635 let span_replace_word = method_span.with_hi(span.hi());
1640 &format!("use of `{}` followed by a function call", name),
1642 format!("{}_{}({})", name, suffix, sugg),
1643 Applicability::HasPlaceholders,
1649 if args.len() == 2 {
1650 match args[1].kind {
1651 hir::ExprKind::Call(ref fun, ref or_args) => {
1652 let or_has_args = !or_args.is_empty();
1653 if !check_unwrap_or_default(cx, name, fun, &args[0], &args[1], or_has_args, expr.span) {
1666 hir::ExprKind::MethodCall(_, span, ref or_args) => check_general_case(
1673 !or_args.is_empty(),
1681 /// Checks for the `EXPECT_FUN_CALL` lint.
1682 #[allow(clippy::too_many_lines)]
1683 fn lint_expect_fun_call(
1684 cx: &LateContext<'_, '_>,
1685 expr: &hir::Expr<'_>,
1688 args: &[hir::Expr<'_>],
1690 // Strip `&`, `as_ref()` and `as_str()` off `arg` until we're left with either a `String` or
1692 fn get_arg_root<'a>(cx: &LateContext<'_, '_>, arg: &'a hir::Expr<'a>) -> &'a hir::Expr<'a> {
1693 let mut arg_root = arg;
1695 arg_root = match &arg_root.kind {
1696 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => expr,
1697 hir::ExprKind::MethodCall(method_name, _, call_args) => {
1698 if call_args.len() == 1
1699 && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref))
1701 let arg_type = cx.tables.expr_ty(&call_args[0]);
1702 let base_type = walk_ptrs_ty(arg_type);
1703 base_type.kind == ty::Str || match_type(cx, base_type, &paths::STRING)
1717 // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be
1718 // converted to string.
1719 fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1720 let arg_ty = cx.tables.expr_ty(arg);
1721 if match_type(cx, arg_ty, &paths::STRING) {
1724 if let ty::Ref(_, ty, ..) = arg_ty.kind {
1725 if ty.kind == ty::Str && can_be_static_str(cx, arg) {
1732 // Check if an expression could have type `&'static str`, knowing that it
1733 // has type `&str` for some lifetime.
1734 fn can_be_static_str(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool {
1736 hir::ExprKind::Lit(_) => true,
1737 hir::ExprKind::Call(fun, _) => {
1738 if let hir::ExprKind::Path(ref p) = fun.kind {
1739 match cx.tables.qpath_res(p, fun.hir_id) {
1740 hir::def::Res::Def(hir::def::DefKind::Fn, def_id)
1741 | hir::def::Res::Def(hir::def::DefKind::AssocFn, def_id) => matches!(
1742 cx.tcx.fn_sig(def_id).output().skip_binder().kind,
1743 ty::Ref(ty::ReStatic, ..)
1751 hir::ExprKind::MethodCall(..) => cx.tables.type_dependent_def_id(arg.hir_id).map_or(false, |method_id| {
1753 cx.tcx.fn_sig(method_id).output().skip_binder().kind,
1754 ty::Ref(ty::ReStatic, ..)
1757 hir::ExprKind::Path(ref p) => match cx.tables.qpath_res(p, arg.hir_id) {
1758 hir::def::Res::Def(hir::def::DefKind::Const, _) | hir::def::Res::Def(hir::def::DefKind::Static, _) => {
1767 fn generate_format_arg_snippet(
1768 cx: &LateContext<'_, '_>,
1770 applicability: &mut Applicability,
1773 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, ref format_arg) = a.kind;
1774 if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.kind;
1775 if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.kind;
1780 .map(|a| snippet_with_applicability(cx, a.span, "..", applicability).into_owned())
1788 fn is_call(node: &hir::ExprKind<'_>) -> bool {
1790 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr) => {
1793 hir::ExprKind::Call(..)
1794 | hir::ExprKind::MethodCall(..)
1795 // These variants are debatable or require further examination
1796 | hir::ExprKind::Match(..)
1797 | hir::ExprKind::Block{ .. } => true,
1802 if args.len() != 2 || name != "expect" || !is_call(&args[1].kind) {
1806 let receiver_type = cx.tables.expr_ty_adjusted(&args[0]);
1807 let closure_args = if match_type(cx, receiver_type, &paths::OPTION) {
1809 } else if match_type(cx, receiver_type, &paths::RESULT) {
1815 let arg_root = get_arg_root(cx, &args[1]);
1817 let span_replace_word = method_span.with_hi(expr.span.hi());
1819 let mut applicability = Applicability::MachineApplicable;
1821 //Special handling for `format!` as arg_root
1823 if let hir::ExprKind::Block(block, None) = &arg_root.kind;
1824 if block.stmts.len() == 1;
1825 if let hir::StmtKind::Local(local) = &block.stmts[0].kind;
1826 if let Some(arg_root) = &local.init;
1827 if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = arg_root.kind;
1828 if is_expn_of(inner_fun.span, "format").is_some() && inner_args.len() == 1;
1829 if let hir::ExprKind::Call(_, format_args) = &inner_args[0].kind;
1831 let fmt_spec = &format_args[0];
1832 let fmt_args = &format_args[1];
1834 let mut args = vec![snippet(cx, fmt_spec.span, "..").into_owned()];
1836 args.extend(generate_format_arg_snippet(cx, fmt_args, &mut applicability));
1838 let sugg = args.join(", ");
1844 &format!("use of `{}` followed by a function call", name),
1846 format!("unwrap_or_else({} panic!({}))", closure_args, sugg),
1854 let mut arg_root_snippet: Cow<'_, _> = snippet_with_applicability(cx, arg_root.span, "..", &mut applicability);
1855 if requires_to_string(cx, arg_root) {
1856 arg_root_snippet.to_mut().push_str(".to_string()");
1863 &format!("use of `{}` followed by a function call", name),
1865 format!("unwrap_or_else({} {{ panic!({}) }})", closure_args, arg_root_snippet),
1870 /// Checks for the `CLONE_ON_COPY` lint.
1871 fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) {
1872 let ty = cx.tables.expr_ty(expr);
1873 if let ty::Ref(_, inner, _) = arg_ty.kind {
1874 if let ty::Ref(_, innermost, _) = inner.kind {
1879 "using `clone` on a double-reference; \
1880 this will copy the reference instead of cloning the inner type",
1882 if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
1883 let mut ty = innermost;
1885 while let ty::Ref(_, inner, _) = ty.kind {
1889 let refs: String = iter::repeat('&').take(n + 1).collect();
1890 let derefs: String = iter::repeat('*').take(n).collect();
1891 let explicit = format!("{}{}::clone({})", refs, ty, snip);
1894 "try dereferencing it",
1895 format!("{}({}{}).clone()", refs, derefs, snip.deref()),
1896 Applicability::MaybeIncorrect,
1900 "or try being explicit about what type to clone",
1902 Applicability::MaybeIncorrect,
1907 return; // don't report clone_on_copy
1911 if is_copy(cx, ty) {
1913 if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
1914 let parent = cx.tcx.hir().get_parent_node(expr.hir_id);
1915 match &cx.tcx.hir().get(parent) {
1916 hir::Node::Expr(parent) => match parent.kind {
1917 // &*x is a nop, &x.clone() is not
1918 hir::ExprKind::AddrOf(..) |
1919 // (*x).func() is useless, x.clone().func() can work in case func borrows mutably
1920 hir::ExprKind::MethodCall(..) => return,
1923 hir::Node::Stmt(stmt) => {
1924 if let hir::StmtKind::Local(ref loc) = stmt.kind {
1925 if let hir::PatKind::Ref(..) = loc.pat.kind {
1926 // let ref y = *x borrows x, let ref y = x.clone() does not
1934 // x.clone() might have dereferenced x, possibly through Deref impls
1935 if cx.tables.expr_ty(arg) == ty {
1936 snip = Some(("try removing the `clone` call", format!("{}", snippet)));
1938 let deref_count = cx
1940 .expr_adjustments(arg)
1943 if let ty::adjustment::Adjust::Deref(_) = adj.kind {
1950 let derefs: String = iter::repeat('*').take(deref_count).collect();
1951 snip = Some(("try dereferencing it", format!("{}{}", derefs, snippet)));
1956 span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
1957 if let Some((text, snip)) = snip {
1958 db.span_suggestion(expr.span, text, snip, Applicability::Unspecified);
1964 fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) {
1965 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
1967 if let ty::Adt(_, subst) = obj_ty.kind {
1968 let caller_type = if match_type(cx, obj_ty, &paths::RC) {
1970 } else if match_type(cx, obj_ty, &paths::ARC) {
1972 } else if match_type(cx, obj_ty, &paths::WEAK_RC) || match_type(cx, obj_ty, &paths::WEAK_ARC) {
1982 "using `.clone()` on a ref-counted pointer",
1985 "{}::<{}>::clone(&{})",
1988 snippet(cx, arg.span, "_")
1990 Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
1995 fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1997 if let Some(arglists) = method_chain_args(arg, &["chars"]) {
1998 let target = &arglists[0][0];
1999 let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
2000 let ref_str = if self_ty.kind == ty::Str {
2002 } else if match_type(cx, self_ty, &paths::STRING) {
2008 let mut applicability = Applicability::MachineApplicable;
2011 STRING_EXTEND_CHARS,
2013 "calling `.extend(_.chars())`",
2016 "{}.push_str({}{})",
2017 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),
2019 snippet_with_applicability(cx, target.span, "_", &mut applicability)
2026 fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2027 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
2028 if match_type(cx, obj_ty, &paths::STRING) {
2029 lint_string_extend(cx, expr, args);
2033 fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) {
2035 let source_type = cx.tables.expr_ty(source);
2036 if let ty::Adt(def, substs) = source_type.kind;
2037 if match_def_path(cx, def.did, &paths::RESULT);
2038 if match_type(cx, substs.type_at(0), &paths::CSTRING);
2042 TEMPORARY_CSTRING_AS_PTR,
2044 "you are getting the inner pointer of a temporary `CString`",
2046 db.note("that pointer will be invalid outside this expression");
2047 db.span_help(unwrap.span, "assign the `CString` to a variable to extend its lifetime");
2053 fn lint_iter_cloned_collect<'a, 'tcx>(
2054 cx: &LateContext<'a, 'tcx>,
2055 expr: &hir::Expr<'_>,
2056 iter_args: &'tcx [hir::Expr<'_>],
2059 if is_type_diagnostic_item(cx, cx.tables.expr_ty(expr), Symbol::intern("vec_type"));
2060 if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0]));
2061 if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite());
2066 ITER_CLONED_COLLECT,
2068 "called `iter().cloned().collect()` on a slice to create a `Vec`. Calling `to_vec()` is both faster and \
2071 ".to_vec()".to_string(),
2072 Applicability::MachineApplicable,
2078 fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, fold_args: &[hir::Expr<'_>], fold_span: Span) {
2079 fn check_fold_with_op(
2080 cx: &LateContext<'_, '_>,
2081 expr: &hir::Expr<'_>,
2082 fold_args: &[hir::Expr<'_>],
2085 replacement_method_name: &str,
2086 replacement_has_args: bool,
2089 // Extract the body of the closure passed to fold
2090 if let hir::ExprKind::Closure(_, _, body_id, _, _) = fold_args[2].kind;
2091 let closure_body = cx.tcx.hir().body(body_id);
2092 let closure_expr = remove_blocks(&closure_body.value);
2094 // Check if the closure body is of the form `acc <op> some_expr(x)`
2095 if let hir::ExprKind::Binary(ref bin_op, ref left_expr, ref right_expr) = closure_expr.kind;
2096 if bin_op.node == op;
2098 // Extract the names of the two arguments to the closure
2099 if let Some(first_arg_ident) = get_arg_name(&closure_body.params[0].pat);
2100 if let Some(second_arg_ident) = get_arg_name(&closure_body.params[1].pat);
2102 if match_var(&*left_expr, first_arg_ident);
2103 if replacement_has_args || match_var(&*right_expr, second_arg_ident);
2106 let mut applicability = Applicability::MachineApplicable;
2107 let sugg = if replacement_has_args {
2109 "{replacement}(|{s}| {r})",
2110 replacement = replacement_method_name,
2111 s = second_arg_ident,
2112 r = snippet_with_applicability(cx, right_expr.span, "EXPR", &mut applicability),
2117 replacement = replacement_method_name,
2124 fold_span.with_hi(expr.span.hi()),
2125 // TODO #2371 don't suggest e.g., .any(|x| f(x)) if we can suggest .any(f)
2126 "this `.fold` can be written more succinctly using another method",
2135 // Check that this is a call to Iterator::fold rather than just some function called fold
2136 if !match_trait_method(cx, expr, &paths::ITERATOR) {
2141 fold_args.len() == 3,
2142 "Expected fold_args to have three entries - the receiver, the initial value and the closure"
2145 // Check if the first argument to .fold is a suitable literal
2146 if let hir::ExprKind::Lit(ref lit) = fold_args[1].kind {
2148 ast::LitKind::Bool(false) => {
2149 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Or, "any", true)
2151 ast::LitKind::Bool(true) => {
2152 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::And, "all", true)
2154 ast::LitKind::Int(0, _) => {
2155 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Add, "sum", false)
2157 ast::LitKind::Int(1, _) => {
2158 check_fold_with_op(cx, expr, fold_args, fold_span, hir::BinOpKind::Mul, "product", false)
2165 fn lint_step_by<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) {
2166 if match_trait_method(cx, expr, &paths::ITERATOR) {
2167 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &args[1]) {
2170 ITERATOR_STEP_BY_ZERO,
2172 "Iterator::step_by(0) will panic at runtime",
2178 fn lint_iter_nth<'a, 'tcx>(
2179 cx: &LateContext<'a, 'tcx>,
2180 expr: &hir::Expr<'_>,
2181 nth_and_iter_args: &[&'tcx [hir::Expr<'tcx>]],
2184 let iter_args = nth_and_iter_args[1];
2185 let mut_str = if is_mut { "_mut" } else { "" };
2186 let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
2188 } else if is_type_diagnostic_item(cx, cx.tables.expr_ty(&iter_args[0]), Symbol::intern("vec_type")) {
2190 } else if match_type(cx, cx.tables.expr_ty(&iter_args[0]), &paths::VEC_DEQUE) {
2193 let nth_args = nth_and_iter_args[0];
2194 lint_iter_nth_zero(cx, expr, &nth_args);
2195 return; // caller is not a type that we want to lint
2202 &format!("called `.iter{0}().nth()` on a {1}", mut_str, caller_type),
2203 &format!("calling `.get{}()` is both faster and more readable", mut_str),
2207 fn lint_iter_nth_zero<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) {
2209 if match_trait_method(cx, expr, &paths::ITERATOR);
2210 if let Some((Constant::Int(0), _)) = constant(cx, cx.tables, &nth_args[1]);
2212 let mut applicability = Applicability::MachineApplicable;
2217 "called `.nth(0)` on a `std::iter::Iterator`",
2219 format!("{}.next()", snippet_with_applicability(cx, nth_args[0].span, "..", &mut applicability)),
2226 fn lint_get_unwrap<'a, 'tcx>(
2227 cx: &LateContext<'a, 'tcx>,
2228 expr: &hir::Expr<'_>,
2229 get_args: &'tcx [hir::Expr<'_>],
2232 // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`,
2233 // because they do not implement `IndexMut`
2234 let mut applicability = Applicability::MachineApplicable;
2235 let expr_ty = cx.tables.expr_ty(&get_args[0]);
2236 let get_args_str = if get_args.len() > 1 {
2237 snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability)
2239 return; // not linting on a .get().unwrap() chain or variant
2242 let caller_type = if derefs_to_slice(cx, &get_args[0], expr_ty).is_some() {
2243 needs_ref = get_args_str.parse::<usize>().is_ok();
2245 } else if is_type_diagnostic_item(cx, expr_ty, Symbol::intern("vec_type")) {
2246 needs_ref = get_args_str.parse::<usize>().is_ok();
2248 } else if match_type(cx, expr_ty, &paths::VEC_DEQUE) {
2249 needs_ref = get_args_str.parse::<usize>().is_ok();
2251 } else if !is_mut && match_type(cx, expr_ty, &paths::HASHMAP) {
2254 } else if !is_mut && match_type(cx, expr_ty, &paths::BTREEMAP) {
2258 return; // caller is not a type that we want to lint
2261 let mut span = expr.span;
2263 // Handle the case where the result is immediately dereferenced
2264 // by not requiring ref and pulling the dereference into the
2268 if let Some(parent) = get_parent_expr(cx, expr);
2269 if let hir::ExprKind::Unary(hir::UnOp::UnDeref, _) = parent.kind;
2276 let mut_str = if is_mut { "_mut" } else { "" };
2277 let borrow_str = if !needs_ref {
2290 "called `.get{0}().unwrap()` on a {1}. Using `[]` is more clear and more concise",
2291 mut_str, caller_type
2297 snippet_with_applicability(cx, get_args[0].span, "_", &mut applicability),
2304 fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
2305 // lint if caller of skip is an Iterator
2306 if match_trait_method(cx, expr, &paths::ITERATOR) {
2311 "called `skip(x).next()` on an iterator",
2312 "this is more succinctly expressed by calling `nth(x)`",
2317 fn derefs_to_slice<'a, 'tcx>(
2318 cx: &LateContext<'a, 'tcx>,
2319 expr: &'tcx hir::Expr<'tcx>,
2321 ) -> Option<&'tcx hir::Expr<'tcx>> {
2322 fn may_slice<'a>(cx: &LateContext<'_, 'a>, ty: Ty<'a>) -> bool {
2324 ty::Slice(_) => true,
2325 ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
2326 ty::Adt(..) => is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type")),
2327 ty::Array(_, size) => {
2328 if let Some(size) = size.try_eval_usize(cx.tcx, cx.param_env) {
2334 ty::Ref(_, inner, _) => may_slice(cx, inner),
2339 if let hir::ExprKind::MethodCall(ref path, _, ref args) = expr.kind {
2340 if path.ident.name == sym!(iter) && may_slice(cx, cx.tables.expr_ty(&args[0])) {
2347 ty::Slice(_) => Some(expr),
2348 ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
2349 ty::Ref(_, inner, _) => {
2350 if may_slice(cx, inner) {
2361 /// lint use of `unwrap()` for `Option`s and `Result`s
2362 fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) {
2363 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
2365 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
2366 Some((OPTION_UNWRAP_USED, "an Option", "None"))
2367 } else if match_type(cx, obj_ty, &paths::RESULT) {
2368 Some((RESULT_UNWRAP_USED, "a Result", "Err"))
2373 if let Some((lint, kind, none_value)) = mess {
2378 &format!("used `unwrap()` on `{}` value", kind,),
2380 "if you don't want to handle the `{}` case gracefully, consider \
2381 using `expect()` to provide a better panic message",
2388 /// lint use of `expect()` for `Option`s and `Result`s
2389 fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) {
2390 let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&expect_args[0]));
2392 let mess = if match_type(cx, obj_ty, &paths::OPTION) {
2393 Some((OPTION_EXPECT_USED, "an Option", "None"))
2394 } else if match_type(cx, obj_ty, &paths::RESULT) {
2395 Some((RESULT_EXPECT_USED, "a Result", "Err"))
2400 if let Some((lint, kind, none_value)) = mess {
2405 &format!("used `expect()` on `{}` value", kind,),
2406 &format!("if this value is an `{}`, it will panic", none_value,),
2411 /// lint use of `ok().expect()` for `Result`s
2412 fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) {
2414 // lint if the caller of `ok()` is a `Result`
2415 if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT);
2416 let result_type = cx.tables.expr_ty(&ok_args[0]);
2417 if let Some(error_type) = get_error_type(cx, result_type);
2418 if has_debug_impl(error_type, cx);
2425 "called `ok().expect()` on a `Result` value",
2426 "you can call `expect()` directly on the `Result`",
2432 /// lint use of `map().flatten()` for `Iterators`
2433 fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>, map_args: &'tcx [hir::Expr<'_>]) {
2434 // lint if caller of `.map().flatten()` is an Iterator
2435 if match_trait_method(cx, expr, &paths::ITERATOR) {
2436 let msg = "called `map(..).flatten()` on an `Iterator`. \
2437 This is more succinctly expressed by calling `.flat_map(..)`";
2438 let self_snippet = snippet(cx, map_args[0].span, "..");
2439 let func_snippet = snippet(cx, map_args[1].span, "..");
2440 let hint = format!("{0}.flat_map({1})", self_snippet, func_snippet);
2446 "try using `flat_map` instead",
2448 Applicability::MachineApplicable,
2453 /// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2454 fn lint_map_unwrap_or_else<'a, 'tcx>(
2455 cx: &LateContext<'a, 'tcx>,
2456 expr: &'tcx hir::Expr<'_>,
2457 map_args: &'tcx [hir::Expr<'_>],
2458 unwrap_args: &'tcx [hir::Expr<'_>],
2460 // lint if the caller of `map()` is an `Option`
2461 let is_option = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION);
2462 let is_result = match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::RESULT);
2464 if is_option || is_result {
2465 // Don't make a suggestion that may fail to compile due to mutably borrowing
2466 // the same variable twice.
2467 let map_mutated_vars = mutated_variables(&map_args[0], cx);
2468 let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
2469 if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
2470 if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2478 let msg = if is_option {
2479 "called `map(f).unwrap_or_else(g)` on an `Option` value. This can be done more directly by calling \
2480 `map_or_else(g, f)` instead"
2482 "called `map(f).unwrap_or_else(g)` on a `Result` value. This can be done more directly by calling \
2483 `.map_or_else(g, f)` instead"
2485 // get snippets for args to map() and unwrap_or_else()
2486 let map_snippet = snippet(cx, map_args[1].span, "..");
2487 let unwrap_snippet = snippet(cx, unwrap_args[1].span, "..");
2488 // lint, with note if neither arg is > 1 line and both map() and
2489 // unwrap_or_else() have the same span
2490 let multiline = map_snippet.lines().count() > 1 || unwrap_snippet.lines().count() > 1;
2491 let same_span = map_args[1].span.ctxt() == unwrap_args[1].span.ctxt();
2492 if same_span && !multiline {
2496 OPTION_MAP_UNWRAP_OR_ELSE
2498 RESULT_MAP_UNWRAP_OR_ELSE
2504 "replace `map({0}).unwrap_or_else({1})` with `map_or_else({1}, {0})`",
2505 map_snippet, unwrap_snippet,
2508 } else if same_span && multiline {
2512 OPTION_MAP_UNWRAP_OR_ELSE
2514 RESULT_MAP_UNWRAP_OR_ELSE
2523 /// lint use of `_.map_or(None, _)` for `Option`s
2524 fn lint_map_or_none<'a, 'tcx>(
2525 cx: &LateContext<'a, 'tcx>,
2526 expr: &'tcx hir::Expr<'_>,
2527 map_or_args: &'tcx [hir::Expr<'_>],
2529 if match_type(cx, cx.tables.expr_ty(&map_or_args[0]), &paths::OPTION) {
2530 // check if the first non-self argument to map_or() is None
2531 let map_or_arg_is_none = if let hir::ExprKind::Path(ref qpath) = map_or_args[1].kind {
2532 match_qpath(qpath, &paths::OPTION_NONE)
2537 if map_or_arg_is_none {
2539 let msg = "called `map_or(None, f)` on an `Option` value. This can be done more directly by calling \
2540 `and_then(f)` instead";
2541 let map_or_self_snippet = snippet(cx, map_or_args[0].span, "..");
2542 let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
2543 let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
2549 "try using `and_then` instead",
2551 Applicability::MachineApplicable,
2557 /// Lint use of `_.and_then(|x| Some(y))` for `Option`s
2558 fn lint_option_and_then_some(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
2559 const LINT_MSG: &str = "using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)`";
2560 const NO_OP_MSG: &str = "using `Option.and_then(Some)`, which is a no-op";
2562 let ty = cx.tables.expr_ty(&args[0]);
2563 if !match_type(cx, ty, &paths::OPTION) {
2567 match args[1].kind {
2568 hir::ExprKind::Closure(_, _, body_id, closure_args_span, _) => {
2569 let closure_body = cx.tcx.hir().body(body_id);
2570 let closure_expr = remove_blocks(&closure_body.value);
2572 if let hir::ExprKind::Call(ref some_expr, ref some_args) = closure_expr.kind;
2573 if let hir::ExprKind::Path(ref qpath) = some_expr.kind;
2574 if match_qpath(qpath, &paths::OPTION_SOME);
2575 if some_args.len() == 1;
2577 let inner_expr = &some_args[0];
2579 if contains_return(inner_expr) {
2583 let some_inner_snip = if inner_expr.span.from_expansion() {
2584 snippet_with_macro_callsite(cx, inner_expr.span, "_")
2586 snippet(cx, inner_expr.span, "_")
2589 let closure_args_snip = snippet(cx, closure_args_span, "..");
2590 let option_snip = snippet(cx, args[0].span, "..");
2591 let note = format!("{}.map({} {})", option_snip, closure_args_snip, some_inner_snip);
2594 OPTION_AND_THEN_SOME,
2599 Applicability::MachineApplicable,
2604 // `_.and_then(Some)` case, which is no-op.
2605 hir::ExprKind::Path(ref qpath) => {
2606 if match_qpath(qpath, &paths::OPTION_SOME) {
2607 let option_snip = snippet(cx, args[0].span, "..");
2608 let note = format!("{}", option_snip);
2611 OPTION_AND_THEN_SOME,
2614 "use the expression directly",
2616 Applicability::MachineApplicable,
2624 /// lint use of `filter().next()` for `Iterators`
2625 fn lint_filter_next<'a, 'tcx>(
2626 cx: &LateContext<'a, 'tcx>,
2627 expr: &'tcx hir::Expr<'_>,
2628 filter_args: &'tcx [hir::Expr<'_>],
2630 // lint if caller of `.filter().next()` is an Iterator
2631 if match_trait_method(cx, expr, &paths::ITERATOR) {
2632 let msg = "called `filter(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2633 `.find(p)` instead.";
2634 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2635 if filter_snippet.lines().count() <= 1 {
2636 // add note if not multi-line
2643 &format!("replace `filter({0}).next()` with `find({0})`", filter_snippet),
2646 span_lint(cx, FILTER_NEXT, expr.span, msg);
2651 /// lint use of `skip_while().next()` for `Iterators`
2652 fn lint_skip_while_next<'a, 'tcx>(
2653 cx: &LateContext<'a, 'tcx>,
2654 expr: &'tcx hir::Expr<'_>,
2655 _skip_while_args: &'tcx [hir::Expr<'_>],
2657 // lint if caller of `.skip_while().next()` is an Iterator
2658 if match_trait_method(cx, expr, &paths::ITERATOR) {
2663 "called `skip_while(p).next()` on an `Iterator`",
2664 "this is more succinctly expressed by calling `.find(!p)` instead",
2669 /// lint use of `filter().map()` for `Iterators`
2670 fn lint_filter_map<'a, 'tcx>(
2671 cx: &LateContext<'a, 'tcx>,
2672 expr: &'tcx hir::Expr<'_>,
2673 _filter_args: &'tcx [hir::Expr<'_>],
2674 _map_args: &'tcx [hir::Expr<'_>],
2676 // lint if caller of `.filter().map()` is an Iterator
2677 if match_trait_method(cx, expr, &paths::ITERATOR) {
2678 let msg = "called `filter(p).map(q)` on an `Iterator`";
2679 let hint = "this is more succinctly expressed by calling `.filter_map(..)` instead";
2680 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2684 /// lint use of `filter_map().next()` for `Iterators`
2685 fn lint_filter_map_next<'a, 'tcx>(
2686 cx: &LateContext<'a, 'tcx>,
2687 expr: &'tcx hir::Expr<'_>,
2688 filter_args: &'tcx [hir::Expr<'_>],
2690 if match_trait_method(cx, expr, &paths::ITERATOR) {
2691 let msg = "called `filter_map(p).next()` on an `Iterator`. This is more succinctly expressed by calling \
2692 `.find_map(p)` instead.";
2693 let filter_snippet = snippet(cx, filter_args[1].span, "..");
2694 if filter_snippet.lines().count() <= 1 {
2701 &format!("replace `filter_map({0}).next()` with `find_map({0})`", filter_snippet),
2704 span_lint(cx, FILTER_MAP_NEXT, expr.span, msg);
2709 /// lint use of `find().map()` for `Iterators`
2710 fn lint_find_map<'a, 'tcx>(
2711 cx: &LateContext<'a, 'tcx>,
2712 expr: &'tcx hir::Expr<'_>,
2713 _find_args: &'tcx [hir::Expr<'_>],
2714 map_args: &'tcx [hir::Expr<'_>],
2716 // lint if caller of `.filter().map()` is an Iterator
2717 if match_trait_method(cx, &map_args[0], &paths::ITERATOR) {
2718 let msg = "called `find(p).map(q)` on an `Iterator`";
2719 let hint = "this is more succinctly expressed by calling `.find_map(..)` instead";
2720 span_lint_and_help(cx, FIND_MAP, expr.span, msg, hint);
2724 /// lint use of `filter_map().map()` for `Iterators`
2725 fn lint_filter_map_map<'a, 'tcx>(
2726 cx: &LateContext<'a, 'tcx>,
2727 expr: &'tcx hir::Expr<'_>,
2728 _filter_args: &'tcx [hir::Expr<'_>],
2729 _map_args: &'tcx [hir::Expr<'_>],
2731 // lint if caller of `.filter().map()` is an Iterator
2732 if match_trait_method(cx, expr, &paths::ITERATOR) {
2733 let msg = "called `filter_map(p).map(q)` on an `Iterator`";
2734 let hint = "this is more succinctly expressed by only calling `.filter_map(..)` instead";
2735 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2739 /// lint use of `filter().flat_map()` for `Iterators`
2740 fn lint_filter_flat_map<'a, 'tcx>(
2741 cx: &LateContext<'a, 'tcx>,
2742 expr: &'tcx hir::Expr<'_>,
2743 _filter_args: &'tcx [hir::Expr<'_>],
2744 _map_args: &'tcx [hir::Expr<'_>],
2746 // lint if caller of `.filter().flat_map()` is an Iterator
2747 if match_trait_method(cx, expr, &paths::ITERATOR) {
2748 let msg = "called `filter(p).flat_map(q)` on an `Iterator`";
2749 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2750 and filtering by returning `iter::empty()`";
2751 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2755 /// lint use of `filter_map().flat_map()` for `Iterators`
2756 fn lint_filter_map_flat_map<'a, 'tcx>(
2757 cx: &LateContext<'a, 'tcx>,
2758 expr: &'tcx hir::Expr<'_>,
2759 _filter_args: &'tcx [hir::Expr<'_>],
2760 _map_args: &'tcx [hir::Expr<'_>],
2762 // lint if caller of `.filter_map().flat_map()` is an Iterator
2763 if match_trait_method(cx, expr, &paths::ITERATOR) {
2764 let msg = "called `filter_map(p).flat_map(q)` on an `Iterator`";
2765 let hint = "this is more succinctly expressed by calling `.flat_map(..)` \
2766 and filtering by returning `iter::empty()`";
2767 span_lint_and_help(cx, FILTER_MAP, expr.span, msg, hint);
2771 /// lint use of `flat_map` for `Iterators` where `flatten` would be sufficient
2772 fn lint_flat_map_identity<'a, 'tcx>(
2773 cx: &LateContext<'a, 'tcx>,
2774 expr: &'tcx hir::Expr<'_>,
2775 flat_map_args: &'tcx [hir::Expr<'_>],
2776 flat_map_span: Span,
2778 if match_trait_method(cx, expr, &paths::ITERATOR) {
2779 let arg_node = &flat_map_args[1].kind;
2781 let apply_lint = |message: &str| {
2785 flat_map_span.with_hi(expr.span.hi()),
2788 "flatten()".to_string(),
2789 Applicability::MachineApplicable,
2794 if let hir::ExprKind::Closure(_, _, body_id, _, _) = arg_node;
2795 let body = cx.tcx.hir().body(*body_id);
2797 if let hir::PatKind::Binding(_, _, binding_ident, _) = body.params[0].pat.kind;
2798 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = body.value.kind;
2800 if path.segments.len() == 1;
2801 if path.segments[0].ident.as_str() == binding_ident.as_str();
2804 apply_lint("called `flat_map(|x| x)` on an `Iterator`");
2809 if let hir::ExprKind::Path(ref qpath) = arg_node;
2811 if match_qpath(qpath, &paths::STD_CONVERT_IDENTITY);
2814 apply_lint("called `flat_map(std::convert::identity)` on an `Iterator`");
2820 /// lint searching an Iterator followed by `is_some()`
2821 fn lint_search_is_some<'a, 'tcx>(
2822 cx: &LateContext<'a, 'tcx>,
2823 expr: &'tcx hir::Expr<'_>,
2824 search_method: &str,
2825 search_args: &'tcx [hir::Expr<'_>],
2826 is_some_args: &'tcx [hir::Expr<'_>],
2829 // lint if caller of search is an Iterator
2830 if match_trait_method(cx, &is_some_args[0], &paths::ITERATOR) {
2832 "called `is_some()` after searching an `Iterator` with {}. This is more succinctly \
2833 expressed by calling `any()`.",
2836 let search_snippet = snippet(cx, search_args[1].span, "..");
2837 if search_snippet.lines().count() <= 1 {
2838 // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
2839 // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
2840 let any_search_snippet = if_chain! {
2841 if search_method == "find";
2842 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
2843 let closure_body = cx.tcx.hir().body(body_id);
2844 if let Some(closure_arg) = closure_body.params.get(0);
2846 if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
2847 Some(search_snippet.replacen('&', "", 1))
2848 } else if let Some(name) = get_arg_name(&closure_arg.pat) {
2849 Some(search_snippet.replace(&format!("*{}", name), &name.as_str()))
2857 // add note if not multi-line
2861 method_span.with_hi(expr.span.hi()),
2866 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
2868 Applicability::MachineApplicable,
2871 span_lint(cx, SEARCH_IS_SOME, expr.span, &msg);
2876 /// Used for `lint_binary_expr_with_method_call`.
2877 #[derive(Copy, Clone)]
2878 struct BinaryExprInfo<'a> {
2879 expr: &'a hir::Expr<'a>,
2880 chain: &'a hir::Expr<'a>,
2881 other: &'a hir::Expr<'a>,
2885 /// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2886 fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
2887 macro_rules! lint_with_both_lhs_and_rhs {
2888 ($func:ident, $cx:expr, $info:ident) => {
2889 if !$func($cx, $info) {
2890 ::std::mem::swap(&mut $info.chain, &mut $info.other);
2891 if $func($cx, $info) {
2898 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp, cx, info);
2899 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp, cx, info);
2900 lint_with_both_lhs_and_rhs!(lint_chars_next_cmp_with_unwrap, cx, info);
2901 lint_with_both_lhs_and_rhs!(lint_chars_last_cmp_with_unwrap, cx, info);
2904 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
2906 cx: &LateContext<'_, '_>,
2907 info: &BinaryExprInfo<'_>,
2908 chain_methods: &[&str],
2909 lint: &'static Lint,
2913 if let Some(args) = method_chain_args(info.chain, chain_methods);
2914 if let hir::ExprKind::Call(ref fun, ref arg_char) = info.other.kind;
2915 if arg_char.len() == 1;
2916 if let hir::ExprKind::Path(ref qpath) = fun.kind;
2917 if let Some(segment) = single_segment_path(qpath);
2918 if segment.ident.name == sym!(Some);
2920 let mut applicability = Applicability::MachineApplicable;
2921 let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
2923 if self_ty.kind != ty::Str {
2931 &format!("you should use the `{}` method", suggest),
2933 format!("{}{}.{}({})",
2934 if info.eq { "" } else { "!" },
2935 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2937 snippet_with_applicability(cx, arg_char[0].span, "_", &mut applicability)),
2948 /// Checks for the `CHARS_NEXT_CMP` lint.
2949 fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2950 lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
2953 /// Checks for the `CHARS_LAST_CMP` lint.
2954 fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2955 if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_LAST_CMP, "ends_with") {
2958 lint_chars_cmp(cx, info, &["chars", "next_back"], CHARS_LAST_CMP, "ends_with")
2962 /// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
2963 fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
2964 cx: &LateContext<'a, 'tcx>,
2965 info: &BinaryExprInfo<'_>,
2966 chain_methods: &[&str],
2967 lint: &'static Lint,
2971 if let Some(args) = method_chain_args(info.chain, chain_methods);
2972 if let hir::ExprKind::Lit(ref lit) = info.other.kind;
2973 if let ast::LitKind::Char(c) = lit.node;
2975 let mut applicability = Applicability::MachineApplicable;
2980 &format!("you should use the `{}` method", suggest),
2982 format!("{}{}.{}('{}')",
2983 if info.eq { "" } else { "!" },
2984 snippet_with_applicability(cx, args[0][0].span, "_", &mut applicability),
2997 /// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
2998 fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
2999 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
3002 /// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
3003 fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
3004 if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
3007 lint_chars_cmp_with_unwrap(cx, info, &["chars", "next_back", "unwrap"], CHARS_LAST_CMP, "ends_with")
3011 /// lint for length-1 `str`s for methods in `PATTERN_METHODS`
3012 fn lint_single_char_pattern<'a, 'tcx>(
3013 cx: &LateContext<'a, 'tcx>,
3014 _expr: &'tcx hir::Expr<'_>,
3015 arg: &'tcx hir::Expr<'_>,
3018 if let hir::ExprKind::Lit(lit) = &arg.kind;
3019 if let ast::LitKind::Str(r, style) = lit.node;
3020 if r.as_str().len() == 1;
3022 let mut applicability = Applicability::MachineApplicable;
3023 let snip = snippet_with_applicability(cx, arg.span, "..", &mut applicability);
3024 let ch = if let ast::StrStyle::Raw(nhash) = style {
3025 let nhash = nhash as usize;
3026 // for raw string: r##"a"##
3027 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
3029 // for regular string: "a"
3030 &snip[1..(snip.len() - 1)]
3032 let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
3035 SINGLE_CHAR_PATTERN,
3037 "single-character string constant used as pattern",
3038 "try using a `char` instead",
3046 /// Checks for the `USELESS_ASREF` lint.
3047 fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, call_name: &str, as_ref_args: &[hir::Expr<'_>]) {
3048 // when we get here, we've already checked that the call name is "as_ref" or "as_mut"
3049 // check if the call is to the actual `AsRef` or `AsMut` trait
3050 if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
3051 // check if the type after `as_ref` or `as_mut` is the same as before
3052 let recvr = &as_ref_args[0];
3053 let rcv_ty = cx.tables.expr_ty(recvr);
3054 let res_ty = cx.tables.expr_ty(expr);
3055 let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty);
3056 let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty);
3057 if base_rcv_ty == base_res_ty && rcv_depth >= res_depth {
3058 // allow the `as_ref` or `as_mut` if it is followed by another method call
3060 if let Some(parent) = get_parent_expr(cx, expr);
3061 if let hir::ExprKind::MethodCall(_, ref span, _) = parent.kind;
3062 if span != &expr.span;
3068 let mut applicability = Applicability::MachineApplicable;
3073 &format!("this call to `{}` does nothing", call_name),
3075 snippet_with_applicability(cx, recvr.span, "_", &mut applicability).to_string(),
3082 fn ty_has_iter_method(cx: &LateContext<'_, '_>, self_ref_ty: Ty<'_>) -> Option<(&'static str, &'static str)> {
3083 has_iter_method(cx, self_ref_ty).map(|ty_name| {
3084 let mutbl = match self_ref_ty.kind {
3085 ty::Ref(_, _, mutbl) => mutbl,
3086 _ => unreachable!(),
3088 let method_name = match mutbl {
3089 hir::Mutability::Not => "iter",
3090 hir::Mutability::Mut => "iter_mut",
3092 (ty_name, method_name)
3096 fn lint_into_iter(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, self_ref_ty: Ty<'_>, method_span: Span) {
3097 if !match_trait_method(cx, expr, &paths::INTO_ITERATOR) {
3100 if let Some((kind, method_name)) = ty_has_iter_method(cx, self_ref_ty) {
3106 "this `.into_iter()` call is equivalent to `.{}()` and will not move the `{}`",
3110 method_name.to_string(),
3111 Applicability::MachineApplicable,
3116 /// lint for `MaybeUninit::uninit().assume_init()` (we already have the latter)
3117 fn lint_maybe_uninit(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, outer: &hir::Expr<'_>) {
3119 if let hir::ExprKind::Call(ref callee, ref args) = expr.kind;
3121 if let hir::ExprKind::Path(ref path) = callee.kind;
3122 if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT);
3123 if !is_maybe_uninit_ty_valid(cx, cx.tables.expr_ty_adjusted(outer));
3127 UNINIT_ASSUMED_INIT,
3129 "this call for this type may be undefined behavior"
3135 fn is_maybe_uninit_ty_valid(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
3137 ty::Array(ref component, _) => is_maybe_uninit_ty_valid(cx, component),
3138 ty::Tuple(ref types) => types.types().all(|ty| is_maybe_uninit_ty_valid(cx, ty)),
3139 ty::Adt(ref adt, _) => {
3140 // needs to be a MaybeUninit
3141 match_def_path(cx, adt.did, &paths::MEM_MAYBEUNINIT)
3147 fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
3152 "this call to `map()` won't have an effect on the call to `count()`",
3153 "make sure you did not confuse `map` with `filter` or `for_each`",
3157 /// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3158 fn lint_option_as_ref_deref<'a, 'tcx>(
3159 cx: &LateContext<'a, 'tcx>,
3160 expr: &hir::Expr<'_>,
3161 as_ref_args: &[hir::Expr<'_>],
3162 map_args: &[hir::Expr<'_>],
3165 let option_ty = cx.tables.expr_ty(&as_ref_args[0]);
3166 if !match_type(cx, option_ty, &paths::OPTION) {
3170 let deref_aliases: [&[&str]; 9] = [
3171 &paths::DEREF_TRAIT_METHOD,
3172 &paths::DEREF_MUT_TRAIT_METHOD,
3173 &paths::CSTRING_AS_C_STR,
3174 &paths::OS_STRING_AS_OS_STR,
3175 &paths::PATH_BUF_AS_PATH,
3176 &paths::STRING_AS_STR,
3177 &paths::STRING_AS_MUT_STR,
3178 &paths::VEC_AS_SLICE,
3179 &paths::VEC_AS_MUT_SLICE,
3182 let is_deref = match map_args[1].kind {
3183 hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3184 hir::ExprKind::Closure(_, _, body_id, _, _) => {
3185 let closure_body = cx.tcx.hir().body(body_id);
3186 let closure_expr = remove_blocks(&closure_body.value);
3188 if let hir::ExprKind::MethodCall(_, _, args) = &closure_expr.kind;
3190 if let hir::ExprKind::Path(qpath) = &args[0].kind;
3191 if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id);
3192 if closure_body.params[0].pat.hir_id == local_id;
3193 let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::<Box<[_]>>();
3194 if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3196 let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap();
3197 deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3208 let current_method = if is_mut {
3209 ".as_mut().map(DerefMut::deref_mut)"
3211 ".as_ref().map(Deref::deref)"
3213 let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3214 let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3215 let suggestion = format!("try using {} instead", method_hint);
3218 "called `{0}` (or with one of deref aliases) on an Option value. \
3219 This can be done more directly by calling `{1}` instead",
3220 current_method, hint
3224 OPTION_AS_REF_DEREF,
3229 Applicability::MachineApplicable,
3234 /// Given a `Result<T, E>` type, return its error type (`E`).
3235 fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
3237 ty::Adt(_, substs) if match_type(cx, ty, &paths::RESULT) => substs.types().nth(1),
3242 /// This checks whether a given type is known to implement Debug.
3243 fn has_debug_impl<'a, 'b>(ty: Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
3245 .get_diagnostic_item(sym::debug_trait)
3246 .map_or(false, |debug| implements_trait(cx, ty, debug, &[]))
3251 StartsWith(&'static str),
3255 const CONVENTIONS: [(Convention, &[SelfKind]); 7] = [
3256 (Convention::Eq("new"), &[SelfKind::No]),
3257 (Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
3258 (Convention::StartsWith("from_"), &[SelfKind::No]),
3259 (Convention::StartsWith("into_"), &[SelfKind::Value]),
3260 (Convention::StartsWith("is_"), &[SelfKind::Ref, SelfKind::No]),
3261 (Convention::Eq("to_mut"), &[SelfKind::RefMut]),
3262 (Convention::StartsWith("to_"), &[SelfKind::Ref]),
3266 const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
3267 ("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
3268 ("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
3269 ("as_ref", 1, SelfKind::Ref, OutType::Ref, "std::convert::AsRef"),
3270 ("bitand", 2, SelfKind::Value, OutType::Any, "std::ops::BitAnd"),
3271 ("bitor", 2, SelfKind::Value, OutType::Any, "std::ops::BitOr"),
3272 ("bitxor", 2, SelfKind::Value, OutType::Any, "std::ops::BitXor"),
3273 ("borrow", 1, SelfKind::Ref, OutType::Ref, "std::borrow::Borrow"),
3274 ("borrow_mut", 1, SelfKind::RefMut, OutType::Ref, "std::borrow::BorrowMut"),
3275 ("clone", 1, SelfKind::Ref, OutType::Any, "std::clone::Clone"),
3276 ("cmp", 2, SelfKind::Ref, OutType::Any, "std::cmp::Ord"),
3277 ("default", 0, SelfKind::No, OutType::Any, "std::default::Default"),
3278 ("deref", 1, SelfKind::Ref, OutType::Ref, "std::ops::Deref"),
3279 ("deref_mut", 1, SelfKind::RefMut, OutType::Ref, "std::ops::DerefMut"),
3280 ("div", 2, SelfKind::Value, OutType::Any, "std::ops::Div"),
3281 ("drop", 1, SelfKind::RefMut, OutType::Unit, "std::ops::Drop"),
3282 ("eq", 2, SelfKind::Ref, OutType::Bool, "std::cmp::PartialEq"),
3283 ("from_iter", 1, SelfKind::No, OutType::Any, "std::iter::FromIterator"),
3284 ("from_str", 1, SelfKind::No, OutType::Any, "std::str::FromStr"),
3285 ("hash", 2, SelfKind::Ref, OutType::Unit, "std::hash::Hash"),
3286 ("index", 2, SelfKind::Ref, OutType::Ref, "std::ops::Index"),
3287 ("index_mut", 2, SelfKind::RefMut, OutType::Ref, "std::ops::IndexMut"),
3288 ("into_iter", 1, SelfKind::Value, OutType::Any, "std::iter::IntoIterator"),
3289 ("mul", 2, SelfKind::Value, OutType::Any, "std::ops::Mul"),
3290 ("neg", 1, SelfKind::Value, OutType::Any, "std::ops::Neg"),
3291 ("next", 1, SelfKind::RefMut, OutType::Any, "std::iter::Iterator"),
3292 ("not", 1, SelfKind::Value, OutType::Any, "std::ops::Not"),
3293 ("rem", 2, SelfKind::Value, OutType::Any, "std::ops::Rem"),
3294 ("shl", 2, SelfKind::Value, OutType::Any, "std::ops::Shl"),
3295 ("shr", 2, SelfKind::Value, OutType::Any, "std::ops::Shr"),
3296 ("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
3300 const PATTERN_METHODS: [(&str, usize); 17] = [
3308 ("split_terminator", 1),
3309 ("rsplit_terminator", 1),
3314 ("match_indices", 1),
3315 ("rmatch_indices", 1),
3316 ("trim_start_matches", 1),
3317 ("trim_end_matches", 1),
3320 #[derive(Clone, Copy, PartialEq, Debug)]
3329 fn matches<'a>(self, cx: &LateContext<'_, 'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool {
3330 fn matches_value(parent_ty: Ty<'_>, ty: Ty<'_>) -> bool {
3331 if ty == parent_ty {
3333 } else if ty.is_box() {
3334 ty.boxed_ty() == parent_ty
3335 } else if ty.is_rc() || ty.is_arc() {
3336 if let ty::Adt(_, substs) = ty.kind {
3337 substs.types().next().map_or(false, |t| t == parent_ty)
3347 cx: &LateContext<'_, 'a>,
3348 mutability: hir::Mutability,
3352 if let ty::Ref(_, t, m) = ty.kind {
3353 return m == mutability && t == parent_ty;
3356 let trait_path = match mutability {
3357 hir::Mutability::Not => &paths::ASREF_TRAIT,
3358 hir::Mutability::Mut => &paths::ASMUT_TRAIT,
3361 let trait_def_id = match get_trait_def_id(cx, trait_path) {
3363 None => return false,
3365 implements_trait(cx, ty, trait_def_id, &[parent_ty.into()])
3369 Self::Value => matches_value(parent_ty, ty),
3370 Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty),
3371 Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty),
3372 Self::No => ty != parent_ty,
3377 fn description(self) -> &'static str {
3379 Self::Value => "self by value",
3380 Self::Ref => "self by reference",
3381 Self::RefMut => "self by mutable reference",
3382 Self::No => "no self",
3389 fn check(&self, other: &str) -> bool {
3391 Self::Eq(this) => this == other,
3392 Self::StartsWith(this) => other.starts_with(this) && this != other,
3397 impl fmt::Display for Convention {
3398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
3400 Self::Eq(this) => this.fmt(f),
3401 Self::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
3406 #[derive(Clone, Copy)]
3415 fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FnRetTy<'_>) -> bool {
3416 let is_unit = |ty: &hir::Ty<'_>| SpanlessEq::new(cx).eq_ty_kind(&ty.kind, &hir::TyKind::Tup(&[]));
3418 (Self::Unit, &hir::FnRetTy::DefaultReturn(_)) => true,
3419 (Self::Unit, &hir::FnRetTy::Return(ref ty)) if is_unit(ty) => true,
3420 (Self::Bool, &hir::FnRetTy::Return(ref ty)) if is_bool(ty) => true,
3421 (Self::Any, &hir::FnRetTy::Return(ref ty)) if !is_unit(ty) => true,
3422 (Self::Ref, &hir::FnRetTy::Return(ref ty)) => matches!(ty.kind, hir::TyKind::Rptr(_, _)),
3428 fn is_bool(ty: &hir::Ty<'_>) -> bool {
3429 if let hir::TyKind::Path(ref p) = ty.kind {
3430 match_qpath(p, &["bool"])
3436 // Returns `true` if `expr` contains a return expression
3437 fn contains_return(expr: &hir::Expr<'_>) -> bool {
3438 struct RetCallFinder {
3442 impl<'tcx> intravisit::Visitor<'tcx> for RetCallFinder {
3443 type Map = Map<'tcx>;
3445 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
3449 if let hir::ExprKind::Ret(..) = &expr.kind {
3452 intravisit::walk_expr(self, expr);
3456 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
3457 intravisit::NestedVisitorMap::None
3461 let mut visitor = RetCallFinder { found: false };
3462 visitor.visit_expr(expr);
3466 fn check_pointer_offset(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3469 if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.tables.expr_ty(&args[0]).kind;
3470 if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty));
3473 span_lint(cx, ZST_OFFSET, expr.span, "offset calculation on zero-sized value");
3478 fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
3479 let ty = cx.tables.expr_ty(&args[0]);
3481 if !match_type(cx, ty, &paths::FILE_TYPE) {
3487 let lint_unary: &str;
3488 let help_unary: &str;
3490 if let Some(parent) = get_parent_expr(cx, expr);
3491 if let hir::ExprKind::Unary(op, _) = parent.kind;
3492 if op == hir::UnOp::UnNot;
3505 let lint_msg = format!("`{}FileType::is_file()` only {} regular files", lint_unary, verb);
3506 let help_msg = format!("use `{}FileType::is_dir()` instead", help_unary);
3507 span_lint_and_help(cx, FILETYPE_IS_FILE, span, &lint_msg, &help_msg);