Skip to content

Commit 092fe20

Browse files
committed
Move deref closure builder to clippy_utils::sugg module
1 parent 5ebede0 commit 092fe20

File tree

2 files changed

+279
-257
lines changed

2 files changed

+279
-257
lines changed
Lines changed: 5 additions & 253 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
1-
use std::iter;
2-
31
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
42
use clippy_utils::source::{snippet, snippet_with_applicability};
3+
use clippy_utils::sugg::deref_closure_args;
54
use clippy_utils::ty::is_type_diagnostic_item;
6-
use clippy_utils::{get_parent_expr_for_hir, is_trait_method, strip_pat_refs};
5+
use clippy_utils::{is_trait_method, strip_pat_refs};
76
use if_chain::if_chain;
87
use rustc_errors::Applicability;
98
use rustc_hir as hir;
10-
use rustc_hir::{self, ExprKind, HirId, MutTy, PatKind, TyKind};
11-
use rustc_infer::infer::TyCtxtInferExt;
9+
use rustc_hir::PatKind;
1210
use rustc_lint::LateContext;
13-
use rustc_middle::hir::place::ProjectionKind;
14-
use rustc_middle::mir::{FakeReadCause, Mutability};
1511
use rustc_middle::ty;
16-
use rustc_span::source_map::{BytePos, Span};
12+
use rustc_span::source_map::Span;
1713
use rustc_span::symbol::sym;
18-
use rustc_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
1914

2015
use super::SEARCH_IS_SOME;
2116

@@ -55,7 +50,7 @@ pub(super) fn check<'tcx>(
5550
} else if let PatKind::Binding(..) = strip_pat_refs(closure_arg.pat).kind {
5651
// `find()` provides a reference to the item, but `any` does not,
5752
// so we should fix item usages for suggestion
58-
if let Some(closure_sugg) = get_closure_suggestion(cx, search_arg) {
53+
if let Some(closure_sugg) = deref_closure_args(cx, search_arg) {
5954
applicability = closure_sugg.applicability;
6055
Some(closure_sugg.suggestion)
6156
} else {
@@ -159,246 +154,3 @@ pub(super) fn check<'tcx>(
159154
}
160155
}
161156
}
162-
163-
#[derive(Debug)]
164-
struct ClosureSugg {
165-
applicability: Applicability,
166-
suggestion: String,
167-
}
168-
169-
// Build suggestion gradually by handling closure arg specific usages,
170-
// such as explicit deref and borrowing cases.
171-
// Returns `None` if no such use cases have been triggered in closure body
172-
fn get_closure_suggestion<'tcx>(cx: &LateContext<'_>, search_expr: &'tcx hir::Expr<'_>) -> Option<ClosureSugg> {
173-
if let hir::ExprKind::Closure(_, fn_decl, body_id, ..) = search_expr.kind {
174-
let closure_body = cx.tcx.hir().body(body_id);
175-
// is closure arg a double reference (i.e.: `|x: &&i32| ...`)
176-
let closure_arg_is_double_ref = if let TyKind::Rptr(_, MutTy { ty, .. }) = fn_decl.inputs[0].kind {
177-
matches!(ty.kind, TyKind::Rptr(_, MutTy { .. }))
178-
} else {
179-
false
180-
};
181-
182-
let mut visitor = DerefDelegate {
183-
cx,
184-
closure_span: search_expr.span,
185-
closure_arg_is_double_ref,
186-
next_pos: search_expr.span.lo(),
187-
suggestion_start: String::new(),
188-
applicability: Applicability::MaybeIncorrect,
189-
};
190-
191-
let fn_def_id = cx.tcx.hir().local_def_id(search_expr.hir_id);
192-
cx.tcx.infer_ctxt().enter(|infcx| {
193-
ExprUseVisitor::new(&mut visitor, &infcx, fn_def_id, cx.param_env, cx.typeck_results())
194-
.consume_body(closure_body);
195-
});
196-
197-
if !visitor.suggestion_start.is_empty() {
198-
return Some(ClosureSugg {
199-
applicability: visitor.applicability,
200-
suggestion: visitor.finish(),
201-
});
202-
}
203-
}
204-
None
205-
}
206-
207-
struct DerefDelegate<'a, 'tcx> {
208-
cx: &'a LateContext<'tcx>,
209-
closure_span: Span,
210-
closure_arg_is_double_ref: bool,
211-
next_pos: BytePos,
212-
suggestion_start: String,
213-
applicability: Applicability,
214-
}
215-
216-
impl DerefDelegate<'_, 'tcx> {
217-
pub fn finish(&mut self) -> String {
218-
let end_span = Span::new(self.next_pos, self.closure_span.hi(), self.closure_span.ctxt(), None);
219-
let end_snip = snippet_with_applicability(self.cx, end_span, "..", &mut self.applicability);
220-
let sugg = format!("{}{}", self.suggestion_start, end_snip);
221-
if self.closure_arg_is_double_ref {
222-
sugg.replacen('&', "", 1)
223-
} else {
224-
sugg
225-
}
226-
}
227-
228-
fn func_takes_arg_by_double_ref(&self, parent_expr: &'tcx hir::Expr<'_>, cmt_hir_id: HirId) -> bool {
229-
let (call_args, inputs) = match parent_expr.kind {
230-
ExprKind::MethodCall(_, _, call_args, _) => {
231-
if let Some(method_did) = self.cx.typeck_results().type_dependent_def_id(parent_expr.hir_id) {
232-
(call_args, self.cx.tcx.fn_sig(method_did).skip_binder().inputs())
233-
} else {
234-
return false;
235-
}
236-
},
237-
ExprKind::Call(func, call_args) => {
238-
let typ = self.cx.typeck_results().expr_ty(func);
239-
(call_args, typ.fn_sig(self.cx.tcx).skip_binder().inputs())
240-
},
241-
_ => return false,
242-
};
243-
244-
iter::zip(call_args, inputs)
245-
.any(|(arg, ty)| arg.hir_id == cmt_hir_id && matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_ref()))
246-
}
247-
}
248-
249-
impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
250-
fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
251-
252-
fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId, _: ty::BorrowKind) {
253-
if let PlaceBase::Local(id) = cmt.place.base {
254-
let map = self.cx.tcx.hir();
255-
let span = map.span(cmt.hir_id);
256-
let start_span = Span::new(self.next_pos, span.lo(), span.ctxt(), None);
257-
let mut start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
258-
259-
// identifier referring to the variable currently triggered (i.e.: `fp`)
260-
let ident_str = map.name(id).to_string();
261-
// full identifier that includes projection (i.e.: `fp.field`)
262-
let ident_str_with_proj = snippet(self.cx, span, "..").to_string();
263-
264-
if cmt.place.projections.is_empty() {
265-
// handle item without any projection, that needs an explicit borrowing
266-
// i.e.: suggest `&x` instead of `x`
267-
self.closure_arg_is_double_ref = false;
268-
self.suggestion_start.push_str(&format!("{}&{}", start_snip, ident_str));
269-
} else {
270-
// cases where a parent `Call` or `MethodCall` is using the item
271-
// i.e.: suggest `.contains(&x)` for `.find(|x| [1, 2, 3].contains(x)).is_none()`
272-
//
273-
// Note about method calls:
274-
// - compiler automatically dereference references if the target type is a reference (works also for
275-
// function call)
276-
// - `self` arguments in the case of `x.is_something()` are also automatically (de)referenced, and
277-
// no projection should be suggested
278-
if let Some(parent_expr) = get_parent_expr_for_hir(self.cx, cmt.hir_id) {
279-
match &parent_expr.kind {
280-
// given expression is the self argument and will be handled completely by the compiler
281-
// i.e.: `|x| x.is_something()`
282-
ExprKind::MethodCall(_, _, [self_expr, ..], _) if self_expr.hir_id == cmt.hir_id => {
283-
self.suggestion_start
284-
.push_str(&format!("{}{}", start_snip, ident_str_with_proj));
285-
self.next_pos = span.hi();
286-
return;
287-
},
288-
// item is used in a call
289-
// i.e.: `Call`: `|x| please(x)` or `MethodCall`: `|x| [1, 2, 3].contains(x)`
290-
ExprKind::Call(_, [call_args @ ..]) | ExprKind::MethodCall(_, _, [_, call_args @ ..], _) => {
291-
let expr = self.cx.tcx.hir().expect_expr(cmt.hir_id);
292-
let arg_ty_kind = self.cx.typeck_results().expr_ty(expr).kind();
293-
294-
if matches!(arg_ty_kind, ty::Ref(_, _, Mutability::Not)) {
295-
// suggest ampersand if call function is taking args by double reference
296-
let takes_arg_by_double_ref =
297-
self.func_takes_arg_by_double_ref(parent_expr, cmt.hir_id);
298-
299-
// compiler will automatically dereference field projection, so no need
300-
// to suggest ampersand, but full identifier that includes projection is required
301-
let has_field_projection = cmt
302-
.place
303-
.projections
304-
.iter()
305-
.any(|proj| matches!(proj.kind, ProjectionKind::Field(..)));
306-
307-
// no need to bind again if the function doesn't take arg by double ref
308-
// and if the item is already a double ref
309-
let ident_sugg = if !call_args.is_empty()
310-
&& !takes_arg_by_double_ref
311-
&& (self.closure_arg_is_double_ref || has_field_projection)
312-
{
313-
let ident = if has_field_projection {
314-
ident_str_with_proj
315-
} else {
316-
ident_str
317-
};
318-
format!("{}{}", start_snip, ident)
319-
} else {
320-
format!("{}&{}", start_snip, ident_str)
321-
};
322-
self.suggestion_start.push_str(&ident_sugg);
323-
self.next_pos = span.hi();
324-
return;
325-
}
326-
327-
self.applicability = Applicability::Unspecified;
328-
},
329-
_ => (),
330-
}
331-
}
332-
333-
let mut replacement_str = ident_str;
334-
let mut projections_handled = false;
335-
cmt.place.projections.iter().enumerate().for_each(|(i, proj)| {
336-
match proj.kind {
337-
// Field projection like `|v| v.foo`
338-
// no adjustment needed here, as field projections are handled by the compiler
339-
ProjectionKind::Field(..) => match cmt.place.ty_before_projection(i).kind() {
340-
ty::Adt(..) | ty::Tuple(_) => {
341-
replacement_str = ident_str_with_proj.clone();
342-
projections_handled = true;
343-
},
344-
_ => (),
345-
},
346-
// Index projection like `|x| foo[x]`
347-
// the index is dropped so we can't get it to build the suggestion,
348-
// so the span is set-up again to get more code, using `span.hi()` (i.e.: `foo[x]`)
349-
// instead of `span.lo()` (i.e.: `foo`)
350-
ProjectionKind::Index => {
351-
let start_span = Span::new(self.next_pos, span.hi(), span.ctxt(), None);
352-
start_snip = snippet_with_applicability(self.cx, start_span, "..", &mut self.applicability);
353-
replacement_str.clear();
354-
projections_handled = true;
355-
},
356-
// note: unable to trigger `Subslice` kind in tests
357-
ProjectionKind::Subslice => (),
358-
ProjectionKind::Deref => {
359-
// explicit deref for arrays should be avoided in the suggestion
360-
// i.e.: `|sub| *sub[1..4].len() == 3` is not expected
361-
if let ty::Ref(_, inner, _) = cmt.place.ty_before_projection(i).kind() {
362-
// dereferencing an array (i.e.: `|sub| sub[1..4].len() == 3`)
363-
if matches!(inner.kind(), ty::Ref(_, innermost, _) if innermost.is_array()) {
364-
projections_handled = true;
365-
}
366-
}
367-
},
368-
}
369-
});
370-
371-
// handle `ProjectionKind::Deref` by removing one explicit deref
372-
// if no special case was detected (i.e.: suggest `*x` instead of `**x`)
373-
if projections_handled {
374-
self.closure_arg_is_double_ref = false;
375-
} else {
376-
let last_deref = cmt
377-
.place
378-
.projections
379-
.iter()
380-
.rposition(|proj| proj.kind == ProjectionKind::Deref);
381-
382-
if let Some(pos) = last_deref {
383-
let mut projections = cmt.place.projections.clone();
384-
projections.truncate(pos);
385-
386-
for item in projections {
387-
if item.kind == ProjectionKind::Deref {
388-
replacement_str = format!("*{}", replacement_str);
389-
}
390-
}
391-
}
392-
}
393-
394-
self.suggestion_start
395-
.push_str(&format!("{}{}", start_snip, replacement_str));
396-
}
397-
self.next_pos = span.hi();
398-
}
399-
}
400-
401-
fn mutate(&mut self, _: &PlaceWithHirId<'tcx>, _: HirId) {}
402-
403-
fn fake_read(&mut self, _: rustc_typeck::expr_use_visitor::Place<'tcx>, _: FakeReadCause, _: HirId) {}
404-
}

0 commit comments

Comments
 (0)