]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/search_is_some.rs
Correct suggestion when dereferencing enough, calling a function
[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::{get_parent_expr_for_hir, 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::{self, ExprKind, HirId, PatKind};
9 use rustc_infer::infer::TyCtxtInferExt;
10 use rustc_lint::LateContext;
11 use rustc_middle::hir::place::ProjectionKind;
12 use rustc_middle::mir::{FakeReadCause, Mutability};
13 use rustc_middle::ty;
14 use rustc_span::source_map::{BytePos, Span};
15 use rustc_span::symbol::sym;
16 use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
17
18 use super::SEARCH_IS_SOME;
19
20 /// lint searching an Iterator followed by `is_some()`
21 /// or calling `find()` on a string followed by `is_some()` or `is_none()`
22 #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
23 pub(super) fn check<'tcx>(
24     cx: &LateContext<'_>,
25     expr: &'tcx hir::Expr<'_>,
26     search_method: &str,
27     is_some: bool,
28     search_recv: &hir::Expr<'_>,
29     search_arg: &'tcx hir::Expr<'_>,
30     is_some_recv: &hir::Expr<'_>,
31     method_span: Span,
32 ) {
33     let option_check_method = if is_some { "is_some" } else { "is_none" };
34     // lint if caller of search is an Iterator
35     if is_trait_method(cx, is_some_recv, sym::Iterator) {
36         let msg = format!(
37             "called `{}()` after searching an `Iterator` with `{}`",
38             option_check_method, search_method
39         );
40         let search_snippet = snippet(cx, search_arg.span, "..");
41         if search_snippet.lines().count() <= 1 {
42             // suggest `any(|x| ..)` instead of `any(|&x| ..)` for `find(|&x| ..).is_some()`
43             // suggest `any(|..| *..)` instead of `any(|..| **..)` for `find(|..| **..).is_some()`
44             let mut applicability = Applicability::MachineApplicable;
45             let any_search_snippet = if_chain! {
46                 if search_method == "find";
47                 if let hir::ExprKind::Closure(_, _, body_id, ..) = search_arg.kind;
48                 let closure_body = cx.tcx.hir().body(body_id);
49                 if let Some(closure_arg) = closure_body.params.get(0);
50                 then {
51                     if let hir::PatKind::Ref(..) = closure_arg.pat.kind {
52                         Some(search_snippet.replacen('&', "", 1))
53                     } else if let PatKind::Binding(_, binding_id, _, _) = strip_pat_refs(closure_arg.pat).kind {
54                         // this binding is composed of at least two levels of references, so we need to remove one
55                         let binding_type = cx.typeck_results().node_type(binding_id);
56                         let innermost_is_ref = if let ty::Ref(_, inner,_) = binding_type.kind() {
57                             matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_ref())
58                         } else {
59                             false
60                         };
61
62                         // `find()` provides a reference to the item, but `any` does not,
63                         // so we should fix item usages for suggestion
64                         if let Some(closure_sugg) = get_closure_suggestion(cx, search_arg, closure_body) {
65                             applicability = closure_sugg.applicability;
66                             if innermost_is_ref {
67                                 Some(closure_sugg.suggestion.replacen('&', "", 1))
68                             } else {
69                                 Some(closure_sugg.suggestion)
70                             }
71                         } else if innermost_is_ref {
72                             Some(search_snippet.replacen('&', "", 1))
73                         } else {
74                             Some(search_snippet.to_string())
75                         }
76                     } else {
77                         None
78                     }
79                 } else {
80                     None
81                 }
82             };
83             // add note if not multi-line
84             if is_some {
85                 span_lint_and_sugg(
86                     cx,
87                     SEARCH_IS_SOME,
88                     method_span.with_hi(expr.span.hi()),
89                     &msg,
90                     "use `any()` instead",
91                     format!(
92                         "any({})",
93                         any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
94                     ),
95                     applicability,
96                 );
97             } else {
98                 let iter = snippet(cx, search_recv.span, "..");
99                 span_lint_and_sugg(
100                     cx,
101                     SEARCH_IS_SOME,
102                     expr.span,
103                     &msg,
104                     "use `!_.any()` instead",
105                     format!(
106                         "!{}.any({})",
107                         iter,
108                         any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
109                     ),
110                     applicability,
111                 );
112             }
113         } else {
114             let hint = format!(
115                 "this is more succinctly expressed by calling `any()`{}",
116                 if option_check_method == "is_none" {
117                     " with negation"
118                 } else {
119                     ""
120                 }
121             );
122             span_lint_and_help(cx, SEARCH_IS_SOME, expr.span, &msg, None, &hint);
123         }
124     }
125     // lint if `find()` is called by `String` or `&str`
126     else if search_method == "find" {
127         let is_string_or_str_slice = |e| {
128             let self_ty = cx.typeck_results().expr_ty(e).peel_refs();
129             if is_type_diagnostic_item(cx, self_ty, sym::String) {
130                 true
131             } else {
132                 *self_ty.kind() == ty::Str
133             }
134         };
135         if_chain! {
136             if is_string_or_str_slice(search_recv);
137             if is_string_or_str_slice(search_arg);
138             then {
139                 let msg = format!("called `{}()` after calling `find()` on a string", option_check_method);
140                 match option_check_method {
141                     "is_some" => {
142                         let mut applicability = Applicability::MachineApplicable;
143                         let find_arg = snippet_with_applicability(cx, search_arg.span, "..", &mut applicability);
144                         span_lint_and_sugg(
145                             cx,
146                             SEARCH_IS_SOME,
147                             method_span.with_hi(expr.span.hi()),
148                             &msg,
149                             "use `contains()` instead",
150                             format!("contains({})", find_arg),
151                             applicability,
152                         );
153                     },
154                     "is_none" => {
155                         let string = snippet(cx, search_recv.span, "..");
156                         let mut applicability = Applicability::MachineApplicable;
157                         let find_arg = snippet_with_applicability(cx, search_arg.span, "..", &mut applicability);
158                         span_lint_and_sugg(
159                             cx,
160                             SEARCH_IS_SOME,
161                             expr.span,
162                             &msg,
163                             "use `!_.contains()` instead",
164                             format!("!{}.contains({})", string, find_arg),
165                             applicability,
166                         );
167                     },
168                     _ => (),
169                 }
170             }
171         }
172     }
173 }
174
175 struct ClosureSugg {
176     applicability: Applicability,
177     suggestion: String,
178 }
179
180 // Build suggestion gradually by handling closure arg specific usages,
181 // such as explicit deref and borrowing cases.
182 // Returns `None` if no such use cases have been triggered in closure body
183 fn get_closure_suggestion<'tcx>(
184     cx: &LateContext<'_>,
185     search_arg: &'tcx hir::Expr<'_>,
186     closure_body: &hir::Body<'_>,
187 ) -> Option<ClosureSugg> {
188     let mut visitor = DerefDelegate {
189         cx,
190         closure_span: search_arg.span,
191         next_pos: search_arg.span.lo(),
192         suggestion_start: String::new(),
193         applicability: Applicability::MachineApplicable,
194     };
195
196     let fn_def_id = cx.tcx.hir().local_def_id(search_arg.hir_id);
197     cx.tcx.infer_ctxt().enter(|infcx| {
198         ExprUseVisitor::new(&mut visitor, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
199             .consume_body(closure_body);
200     });
201
202     if visitor.suggestion_start.is_empty() {
203         None
204     } else {
205         Some(ClosureSugg {
206             applicability: visitor.applicability,
207             suggestion: visitor.finish(),
208         })
209     }
210 }
211
212 struct DerefDelegate<'a, 'tcx> {
213     cx: &'a LateContext<'tcx>,
214     closure_span: Span,
215     next_pos: BytePos,
216     suggestion_start: String,
217     applicability: Applicability,
218 }
219
220 impl DerefDelegate<'_, 'tcx> {
221     pub fn finish(&mut self) -> String {
222         let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt());
223         let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
224         format!("{}{}", self.suggestion_start, end_snip)
225     }
226 }
227
228 impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
229     fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
230
231     fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
232         if let PlaceBase::Local(id) = cmt.place.base {
233             let map = self.cx.tcx.hir();
234             let ident_str = map.name(id).to_string();
235             let span = map.span(cmt.hir_id);
236             let start_span = Span::new(self.next_pos, span.lo(), span.ctxt());
237             let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
238
239             if cmt.place.projections.is_empty() {
240                 // handle item without any projection, that needs an explicit borrowing
241                 // i.e.: suggest `&x` instead of `x`
242                 self.suggestion_start.push_str(&format!("{}&{}", start_snip, ident_str));
243             } else {
244                 // cases where a parent call is using the item
245                 // i.e.: suggest `.contains(&x)` for `.find(|x| [1, 2, 3].contains(x)).is_none()`
246                 if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
247                     if let ExprKind::Call(_, call_args) | ExprKind::MethodCall(_, _, call_args, _) = parent_expr.kind {
248                         let expr = self.cx.tcx.hir().expect_expr(cmt.hir_id);
249                         let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
250
251                         if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
252                             let start_span = Span::new(self.next_pos, span.lo(), span.ctxt());
253                             let start_snip =
254                                 snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
255                             // do not suggest ampersand if the ident is the method caller
256                             let ident_sugg = if !call_args.is_empty() && call_args[0].hir_id == cmt.hir_id {
257                                 format!("{}{}", start_snip, ident_str)
258                             } else {
259                                 format!("{}&{}", start_snip, ident_str)
260                             };
261                             self.suggestion_start.push_str(&ident_sugg);
262                             self.next_pos = span.hi();
263                             return;
264                         } else {
265                             self.applicability = Applicability::Unspecified;
266                         }
267                     }
268                 }
269
270                 // handle item projections by removing one explicit deref
271                 // i.e.: suggest `*x` instead of `**x`
272                 let mut replacement_str = ident_str;
273
274                 // handle index projection first
275                 let index_handled = cmt.place.projections.iter().any(|proj| match proj.kind {
276                     // Index projection like `|x| foo[x]`
277                     // the index is dropped so we can't get it to build the suggestion,
278                     // so the span is set-up again to get more code, using `span.hi()` (i.e.: `foo[x]`)
279                     // instead of `span.lo()` (i.e.: `foo`)
280                     ProjectionKind::Index => {
281                         let start_span = Span::new(self.next_pos, span.hi(), span.ctxt());
282                         start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
283                         replacement_str.clear();
284                         true
285                     },
286                     _ => false,
287                 });
288
289                 // looking for projections other that need to be handled differently
290                 let other_projections_handled = cmt.place.projections.iter().enumerate().any(|(i, proj)| {
291                     match proj.kind {
292                         // Field projection like `|v| v.foo`
293                         ProjectionKind::Field(idx, variant) => match cmt.place.ty_before_projection(i).kind() {
294                             ty::Adt(def, ..) => {
295                                 replacement_str = format!(
296                                     "{}.{}",
297                                     replacement_str,
298                                     def.variants[variant].fields[idx as usize].ident.name.as_str()
299                                 );
300                                 true
301                             },
302                             ty::Tuple(_) => {
303                                 replacement_str = format!("{}.{}", replacement_str, idx);
304                                 true
305                             },
306                             _ => false,
307                         },
308                         // handled previously
309                         ProjectionKind::Index |
310                             // note: unable to trigger `Subslice` kind in tests
311                             ProjectionKind::Subslice => false,
312                         ProjectionKind::Deref => {
313                             // explicit deref for arrays should be avoided in the suggestion
314                             // i.e.: `|sub| *sub[1..4].len() == 3` is not expected
315                             match cmt.place.ty_before_projection(i).kind() {
316                                 // dereferencing an array (i.e.: `|sub| sub[1..4].len() == 3`)
317                                 ty::Ref(_, inner, _) => {
318                                     matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array())
319                                 },
320                                 _ => false,
321                             }
322                         },
323                     }
324                 });
325
326                 // handle `ProjectionKind::Deref` if no special case detected
327                 if !index_handled && !other_projections_handled {
328                     let last_deref = cmt
329                         .place
330                         .projections
331                         .iter()
332                         .rposition(|proj| proj.kind == ProjectionKind::Deref);
333
334                     if let Some(pos) = last_deref {
335                         let mut projections = cmt.place.projections.clone();
336                         projections.truncate(pos);
337
338                         for item in projections {
339                             if item.kind == ProjectionKind::Deref {
340                                 replacement_str = format!("*{}", replacement_str);
341                             }
342                         }
343                     }
344                 }
345
346                 self.suggestion_start
347                     .push_str(&format!("{}{}", start_snip, replacement_str));
348             }
349             self.next_pos = span.hi();
350         }
351     }
352
353     fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
354
355     fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {}
356 }