]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/search_is_some.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / methods / search_is_some.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::source::{snippet, snippet_with_applicability};
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{is_trait_method, strip_pat_refs};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir as hir;
8 use rustc_hir::PatKind;
9 use rustc_lint::LateContext;
10 use rustc_middle::ty;
11 use rustc_span::source_map::Span;
12 use rustc_span::symbol::sym;
13
14 use super::SEARCH_IS_SOME;
15
16 /// lint searching an Iterator followed by `is_some()`
17 /// or calling `find()` on a string followed by `is_some()` or `is_none()`
18 #[allow(clippy::too_many_lines)]
19 pub(super) fn check<'tcx>(
20     cx: &LateContext<'tcx>,
21     expr: &'tcx hir::Expr<'_>,
22     search_method: &str,
23     option_check_method: &str,
24     search_args: &'tcx [hir::Expr<'_>],
25     is_some_args: &'tcx [hir::Expr<'_>],
26     method_span: Span,
27 ) {
28     // lint if caller of search is an Iterator
29     if is_trait_method(cx, &is_some_args[0], sym::Iterator) {
30         let msg = format!(
31             "called `{}()` after searching an `Iterator` with `{}`",
32             option_check_method, search_method
33         );
34         let search_snippet = snippet(cx, search_args[1].span, "..");
35         if search_snippet.lines().count() <= 1 {
36             // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
37             // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
38             let any_search_snippet = if_chain! {
39                 if search_method == "find";
40                 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_args[1].kind;
41                 let closure_body = cx.tcx.hir().body(body_id);
42                 if let Some(closure_arg) = closure_body.params.get(0);
43                 then {
44                     if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
45                         Some(search_snippet.replacen('&', "", 1))
46                     } else if let PatKind::Binding(_, _, ident, _) = strip_pat_refs(&closure_arg.pat).kind {
47                         let name = &*ident.name.as_str();
48                         Some(search_snippet.replace(&format!("*{}", name), name))
49                     } else {
50                         None
51                     }
52                 } else {
53                     None
54                 }
55             };
56             // add note if not multi-line
57             match option_check_method {
58                 "is_some" => {
59                     span_lint_and_sugg(
60                         cx,
61                         SEARCH_IS_SOME,
62                         method_span.with_hi(expr.span.hi()),
63                         &msg,
64                         "use `any()` instead",
65                         format!(
66                             "any({})",
67                             any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
68                         ),
69                         Applicability::MachineApplicable,
70                     );
71                 },
72                 "is_none" => {
73                     let iter = snippet(cx, search_args[0].span, "..");
74                     span_lint_and_sugg(
75                         cx,
76                         SEARCH_IS_SOME,
77                         expr.span,
78                         &msg,
79                         "use `!_.any()` instead",
80                         format!(
81                             "!{}.any({})",
82                             iter,
83                             any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
84                         ),
85                         Applicability::MachineApplicable,
86                     );
87                 },
88                 _ => (),
89             }
90         } else {
91             let hint = format!(
92                 "this is more succinctly expressed by calling `any()`{}",
93                 if option_check_method == "is_none" {
94                     " with negation"
95                 } else {
96                     ""
97                 }
98             );
99             span_lint_and_help(cx, SEARCH_IS_SOME, expr.span, &msg, None, &hint);
100         }
101     }
102     // lint if `find()` is called by `String` or `&str`
103     else if search_method == "find" {
104         let is_string_or_str_slice = |e| {
105             let self_ty = cx.typeck_results().expr_ty(e).peel_refs();
106             if is_type_diagnostic_item(cx, self_ty, sym::string_type) {
107                 true
108             } else {
109                 *self_ty.kind() == ty::Str
110             }
111         };
112         if_chain! {
113             if is_string_or_str_slice(&search_args[0]);
114             if is_string_or_str_slice(&search_args[1]);
115             then {
116                 let msg = format!("called `{}()` after calling `find()` on a string", option_check_method);
117                 match option_check_method {
118                     "is_some" => {
119                         let mut applicability = Applicability::MachineApplicable;
120                         let find_arg = snippet_with_applicability(cx, search_args[1].span, "..", &mut applicability);
121                         span_lint_and_sugg(
122                             cx,
123                             SEARCH_IS_SOME,
124                             method_span.with_hi(expr.span.hi()),
125                             &msg,
126                             "use `contains()` instead",
127                             format!("contains({})", find_arg),
128                             applicability,
129                         );
130                     },
131                     "is_none" => {
132                         let string = snippet(cx, search_args[0].span, "..");
133                         let mut applicability = Applicability::MachineApplicable;
134                         let find_arg = snippet_with_applicability(cx, search_args[1].span, "..", &mut applicability);
135                         span_lint_and_sugg(
136                             cx,
137                             SEARCH_IS_SOME,
138                             expr.span,
139                             &msg,
140                             "use `!_.contains()` instead",
141                             format!("!{}.contains({})", string, find_arg),
142                             applicability,
143                         );
144                     },
145                     _ => (),
146                 }
147             }
148         }
149     }
150 }