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;
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};
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};
18 use super::SEARCH_IS_SOME;
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>(
25 expr: &'tcx hir::Expr<'_>,
28 search_recv: &hir::Expr<'_>,
29 search_arg: &'tcx hir::Expr<'_>,
30 is_some_recv: &hir::Expr<'_>,
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) {
37 "called `{}()` after searching an `Iterator` with `{}`",
38 option_check_method, search_method
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);
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())
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;
67 Some(closure_sugg.suggestion.replacen('&', "", 1))
69 Some(closure_sugg.suggestion)
71 } else if innermost_is_ref {
72 Some(search_snippet.replacen('&', "", 1))
74 Some(search_snippet.to_string())
83 // add note if not multi-line
88 method_span.with_hi(expr.span.hi()),
90 "use `any()` instead",
93 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
98 let iter = snippet(cx, search_recv.span, "..");
104 "use `!_.any()` instead",
108 any_search_snippet.as_ref().map_or(&*search_snippet, String::as_str)
115 "this is more succinctly expressed by calling `any()`{}",
116 if option_check_method == "is_none" {
122 span_lint_and_help(cx, SEARCH_IS_SOME, expr.span, &msg, None, &hint);
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) {
132 *self_ty.kind() == ty::Str
136 if is_string_or_str_slice(search_recv);
137 if is_string_or_str_slice(search_arg);
139 let msg = format!("called `{}()` after calling `find()` on a string", option_check_method);
140 match option_check_method {
142 let mut applicability = Applicability::MachineApplicable;
143 let find_arg = snippet_with_applicability(cx, search_arg.span, "..", &mut applicability);
147 method_span.with_hi(expr.span.hi()),
149 "use `contains()` instead",
150 format!("contains({})", find_arg),
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);
163 "use `!_.contains()` instead",
164 format!("!{}.contains({})", string, find_arg),
176 applicability: Applicability,
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 {
190 closure_span: search_arg.span,
191 next_pos: search_arg.span.lo(),
192 suggestion_start: String::new(),
193 applicability: Applicability::MachineApplicable,
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);
202 if visitor.suggestion_start.is_empty() {
206 applicability: visitor.applicability,
207 suggestion: visitor.finish(),
212 struct DerefDelegate<'a, 'tcx> {
213 cx: &'a LateContext<'tcx>,
216 suggestion_start: String,
217 applicability: Applicability,
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)
228 impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
229 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
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);
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));
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();
251 if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
252 let start_span = Span::new(self.next_pos, span.lo(), span.ctxt());
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)
259 format!("{}&{}", start_snip, ident_str)
261 self.suggestion_start.push_str(&ident_sugg);
262 self.next_pos = span.hi();
265 self.applicability = Applicability::Unspecified;
270 // handle item projections by removing one explicit deref
271 // i.e.: suggest `*x` instead of `**x`
272 let mut replacement_str = ident_str;
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();
289 // looking for projections other that need to be handled differently
290 let other_projections_handled = cmt.place.projections.iter().enumerate().any(|(i, proj)| {
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!(
298 def.variants[variant].fields[idx as usize].ident.name.as_str()
303 replacement_str = format!("{}.{}", replacement_str, idx);
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())
326 // handle `ProjectionKind::Deref` if no special case detected
327 if !index_handled && !other_projections_handled {
332 .rposition(|proj| proj.kind == ProjectionKind::Deref);
334 if let Some(pos) = last_deref {
335 let mut projections = cmt.place.projections.clone();
336 projections.truncate(pos);
338 for item in projections {
339 if item.kind == ProjectionKind::Deref {
340 replacement_str = format!("*{}", replacement_str);
346 self.suggestion_start
347 .push_str(&format!("{}{}", start_snip, replacement_str));
349 self.next_pos = span.hi();
353 fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
355 fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {}