1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then};
2 use clippy_utils::mir::{enclosing_mir, expr_local, local_assignments, used_exactly_once, PossibleBorrowerMap};
3 use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
4 use clippy_utils::sugg::has_enclosing_paren;
5 use clippy_utils::ty::{expr_sig, is_copy, peel_mid_ty_refs, ty_sig, variant_of_res};
7 fn_def_id, get_parent_expr, get_parent_expr_for_hir, is_lint_allowed, meets_msrv, msrvs, path_to_local,
10 use rustc_ast::util::parser::{PREC_POSTFIX, PREC_PREFIX};
11 use rustc_data_structures::fx::FxIndexMap;
12 use rustc_errors::Applicability;
13 use rustc_hir::intravisit::{walk_ty, Visitor};
16 def_id::{DefId, LocalDefId},
17 BindingAnnotation, Body, BodyId, BorrowKind, Closure, Expr, ExprKind, FnRetTy, GenericArg, HirId, ImplItem,
18 ImplItemKind, Item, ItemKind, Local, MatchSource, Mutability, Node, Pat, PatKind, Path, QPath, TraitItem,
19 TraitItemKind, TyKind, UnOp,
21 use rustc_index::bit_set::BitSet;
22 use rustc_infer::infer::TyCtxtInferExt;
23 use rustc_lint::{LateContext, LateLintPass};
24 use rustc_middle::mir::{Rvalue, StatementKind};
25 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
26 use rustc_middle::ty::{
27 self, Binder, BoundVariableKind, EarlyBinder, FnSig, GenericArgKind, List, ParamTy, PredicateKind,
28 ProjectionPredicate, Ty, TyCtxt, TypeVisitable, TypeckResults,
30 use rustc_semver::RustcVersion;
31 use rustc_session::{declare_tool_lint, impl_lint_pass};
32 use rustc_span::{symbol::sym, Span, Symbol};
33 use rustc_trait_selection::infer::InferCtxtExt as _;
34 use rustc_trait_selection::traits::{query::evaluate_obligation::InferCtxtExt as _, Obligation, ObligationCause};
35 use std::collections::VecDeque;
37 declare_clippy_lint! {
39 /// Checks for explicit `deref()` or `deref_mut()` method calls.
41 /// ### Why is this bad?
42 /// Dereferencing by `&*x` or `&mut *x` is clearer and more concise,
43 /// when not part of a method chain.
47 /// use std::ops::Deref;
48 /// let a: &mut String = &mut String::from("foo");
49 /// let b: &str = a.deref();
54 /// let a: &mut String = &mut String::from("foo");
58 /// This lint excludes:
60 /// let _ = d.unwrap().deref();
62 #[clippy::version = "1.44.0"]
63 pub EXPLICIT_DEREF_METHODS,
65 "Explicit use of deref or deref_mut method while not in a method chain."
68 declare_clippy_lint! {
70 /// Checks for address of operations (`&`) that are going to
71 /// be dereferenced immediately by the compiler.
73 /// ### Why is this bad?
74 /// Suggests that the receiver of the expression borrows
79 /// fn fun(_a: &i32) {}
81 /// let x: &i32 = &&&&&&5;
87 /// # fn fun(_a: &i32) {}
91 #[clippy::version = "pre 1.29.0"]
94 "taking a reference that is going to be automatically dereferenced"
97 declare_clippy_lint! {
99 /// Checks for `ref` bindings which create a reference to a reference.
101 /// ### Why is this bad?
102 /// The address-of operator at the use site is clearer about the need for a reference.
106 /// let x = Some("");
107 /// if let Some(ref x) = x {
114 /// let x = Some("");
115 /// if let Some(x) = x {
119 #[clippy::version = "1.54.0"]
120 pub REF_BINDING_TO_REFERENCE,
122 "`ref` binding to a reference"
125 declare_clippy_lint! {
127 /// Checks for dereferencing expressions which would be covered by auto-deref.
129 /// ### Why is this bad?
130 /// This unnecessarily complicates the code.
134 /// let x = String::new();
135 /// let y: &str = &*x;
139 /// let x = String::new();
140 /// let y: &str = &x;
142 #[clippy::version = "1.64.0"]
143 pub EXPLICIT_AUTO_DEREF,
145 "dereferencing when the compiler would automatically dereference"
148 impl_lint_pass!(Dereferencing<'_> => [
149 EXPLICIT_DEREF_METHODS,
151 REF_BINDING_TO_REFERENCE,
156 pub struct Dereferencing<'tcx> {
157 state: Option<(State, StateData)>,
159 // While parsing a `deref` method call in ufcs form, the path to the function is itself an
160 // expression. This is to store the id of that expression so it can be skipped when
161 // `check_expr` is called for it.
162 skip_expr: Option<HirId>,
164 /// The body the first local was found in. Used to emit lints when the traversal of the body has
165 /// been finished. Note we can't lint at the end of every body as they can be nested within each
167 current_body: Option<BodyId>,
169 /// The list of locals currently being checked by the lint.
170 /// If the value is `None`, then the binding has been seen as a ref pattern, but is not linted.
171 /// This is needed for or patterns where one of the branches can be linted, but another can not
174 /// e.g. `m!(x) | Foo::Bar(ref x)`
175 ref_locals: FxIndexMap<HirId, Option<RefPat>>,
177 /// Stack of (body owner, `PossibleBorrowerMap`) pairs. Used by
178 /// `needless_borrow_impl_arg_position` to determine when a borrowed expression can instead
180 possible_borrowers: Vec<(LocalDefId, PossibleBorrowerMap<'tcx, 'tcx>)>,
182 // `IntoIterator` for arrays requires Rust 1.53.
183 msrv: Option<RustcVersion>,
186 impl<'tcx> Dereferencing<'tcx> {
188 pub fn new(msrv: Option<RustcVersion>) -> Self {
191 ..Dereferencing::default()
198 /// Span of the top level expression
205 struct DerefedBorrow {
208 snip_expr: Option<HirId>,
213 // Any number of deref method calls.
215 // The number of calls in a sequence which changed the referenced type
216 ty_changed_count: usize,
218 /// The required mutability
219 target_mut: Mutability,
221 DerefedBorrow(DerefedBorrow),
223 mutability: Option<Mutability>,
229 mutability: Mutability,
232 mutability: Mutability,
236 // A reference operation considered by this lint pass
244 /// Whether every usage of the binding is dereferenced.
246 /// The spans of all the ref bindings for this local.
248 /// The applicability of this suggestion.
250 /// All the replacements which need to be made.
251 replacements: Vec<(Span, String)>,
252 /// The [`HirId`] that the lint should be emitted at.
256 impl<'tcx> LateLintPass<'tcx> for Dereferencing<'tcx> {
257 #[expect(clippy::too_many_lines)]
258 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
259 // Skip path expressions from deref calls. e.g. `Deref::deref(e)`
260 if Some(expr.hir_id) == self.skip_expr.take() {
264 if let Some(local) = path_to_local(expr) {
265 self.check_local_usage(cx, expr, local);
268 // Stop processing sub expressions when a macro call is seen
269 if expr.span.from_expansion() {
270 if let Some((state, data)) = self.state.take() {
271 report(cx, expr, state, data);
276 let typeck = cx.typeck_results();
277 let (kind, sub_expr) = if let Some(x) = try_parse_ref_op(cx.tcx, typeck, expr) {
280 // The whole chain of reference operations has been seen
281 if let Some((state, data)) = self.state.take() {
282 report(cx, expr, state, data);
287 match (self.state.take(), kind) {
289 let expr_ty = typeck.expr_ty(expr);
290 let (position, adjustments) = walk_parents(cx, &mut self.possible_borrowers, expr, self.msrv);
293 if let Position::FieldAccess {
297 && !ty_contains_field(typeck.expr_ty(sub_expr), name)
300 State::ExplicitDerefField { name },
301 StateData { span: expr.span, hir_id: expr.hir_id, position },
303 } else if position.is_deref_stable() {
305 State::ExplicitDeref { mutability: None },
306 StateData { span: expr.span, hir_id: expr.hir_id, position },
310 RefOp::Method(target_mut)
311 if !is_lint_allowed(cx, EXPLICIT_DEREF_METHODS, expr.hir_id)
312 && position.lint_explicit_deref() =>
314 let ty_changed_count = usize::from(!deref_method_same_type(expr_ty, typeck.expr_ty(sub_expr)));
318 is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
328 RefOp::AddrOf(mutability) => {
329 // Find the number of times the borrow is auto-derefed.
330 let mut iter = adjustments.iter();
331 let mut deref_count = 0usize;
332 let next_adjust = loop {
335 if !matches!(adjust.kind, Adjust::Deref(_)) {
337 } else if !adjust.target.is_ref() {
347 // Determine the required number of references before any can be removed. In all cases the
348 // reference made by the current expression will be removed. After that there are four cases to
351 // 1. Auto-borrow will trigger in the current position, so no further references are required.
352 // 2. Auto-deref ends at a reference, or the underlying type, so one extra needs to be left to
353 // handle the automatically inserted re-borrow.
354 // 3. Auto-deref hits a user-defined `Deref` impl, so at least one reference needs to exist to
356 // 4. If the chain of non-user-defined derefs ends with a mutable re-borrow, and re-borrow
357 // adjustments will not be inserted automatically, then leave one further reference to avoid
358 // moving a mutable borrow.
360 // fn foo<T>(x: &mut Option<&mut T>, y: &mut T) {
362 // // Removing the borrow will cause `x` to be moved
363 // Some(x) => &mut *x,
368 "this expression creates a reference which is immediately dereferenced by the compiler";
369 let borrow_msg = "this expression borrows a value the compiler would automatically borrow";
370 let impl_msg = "the borrowed expression implements the required traits";
372 let (required_refs, msg, snip_expr) = if position.can_auto_borrow() {
373 (1, if deref_count == 1 { borrow_msg } else { deref_msg }, None)
374 } else if let Position::ImplArg(hir_id) = position {
375 (0, impl_msg, Some(hir_id))
376 } else if let Some(&Adjust::Borrow(AutoBorrow::Ref(_, mutability))) =
377 next_adjust.map(|a| &a.kind)
379 if matches!(mutability, AutoBorrowMutability::Mut { .. }) && !position.is_reborrow_stable()
389 if deref_count >= required_refs {
391 State::DerefedBorrow(DerefedBorrow {
392 // One of the required refs is for the current borrow expression, the remaining ones
393 // can't be removed without breaking the code. See earlier comment.
394 count: deref_count - required_refs,
398 StateData { span: expr.span, hir_id: expr.hir_id, position },
400 } else if position.is_deref_stable()
401 // Auto-deref doesn't combine with other adjustments
402 && next_adjust.map_or(true, |a| matches!(a.kind, Adjust::Deref(_) | Adjust::Borrow(_)))
403 && iter.all(|a| matches!(a.kind, Adjust::Deref(_) | Adjust::Borrow(_)))
406 State::Borrow { mutability },
415 RefOp::Method(..) => (),
431 ty_changed_count: if deref_method_same_type(typeck.expr_ty(expr), typeck.expr_ty(sub_expr)) {
436 is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
442 (Some((State::DerefedBorrow(state), data)), RefOp::AddrOf(_)) if state.count != 0 => {
444 State::DerefedBorrow(DerefedBorrow {
445 count: state.count - 1,
451 (Some((State::DerefedBorrow(state), data)), RefOp::AddrOf(mutability)) => {
452 let position = data.position;
453 report(cx, expr, State::DerefedBorrow(state), data);
454 if position.is_deref_stable() {
456 State::Borrow { mutability },
465 (Some((State::DerefedBorrow(state), data)), RefOp::Deref) => {
466 let position = data.position;
467 report(cx, expr, State::DerefedBorrow(state), data);
468 if let Position::FieldAccess{name, ..} = position
469 && !ty_contains_field(typeck.expr_ty(sub_expr), name)
472 State::ExplicitDerefField { name },
473 StateData { span: expr.span, hir_id: expr.hir_id, position },
475 } else if position.is_deref_stable() {
477 State::ExplicitDeref { mutability: None },
478 StateData { span: expr.span, hir_id: expr.hir_id, position },
483 (Some((State::Borrow { mutability }, data)), RefOp::Deref) => {
484 if typeck.expr_ty(sub_expr).is_ref() {
485 self.state = Some((State::Reborrow { mutability }, data));
488 State::ExplicitDeref {
489 mutability: Some(mutability),
495 (Some((State::Reborrow { mutability }, data)), RefOp::Deref) => {
497 State::ExplicitDeref {
498 mutability: Some(mutability),
503 (state @ Some((State::ExplicitDeref { .. }, _)), RefOp::Deref) => {
506 (Some((State::ExplicitDerefField { name }, data)), RefOp::Deref)
507 if !ty_contains_field(typeck.expr_ty(sub_expr), name) =>
509 self.state = Some((State::ExplicitDerefField { name }, data));
512 (Some((state, data)), _) => report(cx, expr, state, data),
516 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
517 if let PatKind::Binding(BindingAnnotation::REF, id, name, _) = pat.kind {
518 if let Some(opt_prev_pat) = self.ref_locals.get_mut(&id) {
519 // This binding id has been seen before. Add this pattern to the list of changes.
520 if let Some(prev_pat) = opt_prev_pat {
521 if pat.span.from_expansion() {
522 // Doesn't match the context of the previous pattern. Can't lint here.
523 *opt_prev_pat = None;
525 prev_pat.spans.push(pat.span);
526 prev_pat.replacements.push((
528 snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut prev_pat.app)
538 if !pat.span.from_expansion();
539 if let ty::Ref(_, tam, _) = *cx.typeck_results().pat_ty(pat).kind();
540 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
541 if let ty::Ref(_, _, Mutability::Not) = *tam.kind();
543 let mut app = Applicability::MachineApplicable;
544 let snip = snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut app).0;
545 self.current_body = self.current_body.or(cx.enclosing_body);
546 self.ref_locals.insert(
550 spans: vec![pat.span],
552 replacements: vec![(pat.span, snip.into())],
561 fn check_body_post(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
562 if self.possible_borrowers.last().map_or(false, |&(local_def_id, _)| {
563 local_def_id == cx.tcx.hir().body_owner_def_id(body.id())
565 self.possible_borrowers.pop();
568 if Some(body.id()) == self.current_body {
569 for pat in self.ref_locals.drain(..).filter_map(|(_, x)| x) {
570 let replacements = pat.replacements;
572 let lint = if pat.always_deref {
575 REF_BINDING_TO_REFERENCE
577 span_lint_hir_and_then(
582 "this pattern creates a reference to a reference",
584 diag.multipart_suggestion("try this", replacements, app);
588 self.current_body = None;
592 extract_msrv_attr!(LateContext);
595 fn try_parse_ref_op<'tcx>(
597 typeck: &'tcx TypeckResults<'_>,
598 expr: &'tcx Expr<'_>,
599 ) -> Option<(RefOp, &'tcx Expr<'tcx>)> {
600 let (def_id, arg) = match expr.kind {
601 ExprKind::MethodCall(_, arg, [], _) => (typeck.type_dependent_def_id(expr.hir_id)?, arg),
604 kind: ExprKind::Path(path),
609 ) => (typeck.qpath_res(path, *hir_id).opt_def_id()?, arg),
610 ExprKind::Unary(UnOp::Deref, sub_expr) if !typeck.expr_ty(sub_expr).is_unsafe_ptr() => {
611 return Some((RefOp::Deref, sub_expr));
613 ExprKind::AddrOf(BorrowKind::Ref, mutability, sub_expr) => return Some((RefOp::AddrOf(mutability), sub_expr)),
616 if tcx.is_diagnostic_item(sym::deref_method, def_id) {
617 Some((RefOp::Method(Mutability::Not), arg))
618 } else if tcx.trait_of_item(def_id)? == tcx.lang_items().deref_mut_trait()? {
619 Some((RefOp::Method(Mutability::Mut), arg))
625 // Checks whether the type for a deref call actually changed the type, not just the mutability of
627 fn deref_method_same_type<'tcx>(result_ty: Ty<'tcx>, arg_ty: Ty<'tcx>) -> bool {
628 match (result_ty.kind(), arg_ty.kind()) {
629 (ty::Ref(_, result_ty, _), ty::Ref(_, arg_ty, _)) => result_ty == arg_ty,
631 // The result type for a deref method is always a reference
632 // Not matching the previous pattern means the argument type is not a reference
633 // This means that the type did change
638 /// The position of an expression relative to it's parent.
639 #[derive(Clone, Copy, Debug)]
642 /// The method is defined on a reference type. e.g. `impl Foo for &T`
643 MethodReceiverRefImpl,
649 }, // union fields cannot be auto borrowed
652 /// Any other location which will trigger auto-deref to a specific time.
653 /// Contains the precedence of the parent expression and whether the target type is sized.
654 DerefStable(i8, bool),
655 /// Any other location which will trigger auto-reborrowing.
656 /// Contains the precedence of the parent expression.
658 /// Contains the precedence of the parent expression.
662 fn is_deref_stable(self) -> bool {
663 matches!(self, Self::DerefStable(..))
666 fn is_reborrow_stable(self) -> bool {
667 matches!(self, Self::DerefStable(..) | Self::ReborrowStable(_))
670 fn can_auto_borrow(self) -> bool {
673 Self::MethodReceiver | Self::FieldAccess { of_union: false, .. } | Self::Callee
677 fn lint_explicit_deref(self) -> bool {
678 matches!(self, Self::Other(_) | Self::DerefStable(..) | Self::ReborrowStable(_))
681 fn precedence(self) -> i8 {
684 | Self::MethodReceiverRefImpl
686 | Self::FieldAccess { .. }
687 | Self::Postfix => PREC_POSTFIX,
688 Self::ImplArg(_) | Self::Deref => PREC_PREFIX,
689 Self::DerefStable(p, _) | Self::ReborrowStable(p) | Self::Other(p) => p,
694 /// Walks up the parent expressions attempting to determine both how stable the auto-deref result
695 /// is, and which adjustments will be applied to it. Note this will not consider auto-borrow
696 /// locations as those follow different rules.
697 #[expect(clippy::too_many_lines)]
698 fn walk_parents<'tcx>(
699 cx: &LateContext<'tcx>,
700 possible_borrowers: &mut Vec<(LocalDefId, PossibleBorrowerMap<'tcx, 'tcx>)>,
702 msrv: Option<RustcVersion>,
703 ) -> (Position, &'tcx [Adjustment<'tcx>]) {
704 let mut adjustments = [].as_slice();
705 let mut precedence = 0i8;
706 let ctxt = e.span.ctxt();
707 let position = walk_to_expr_usage(cx, e, &mut |parent, child_id| {
708 // LocalTableInContext returns the wrong lifetime, so go use `expr_adjustments` instead.
709 if adjustments.is_empty() && let Node::Expr(e) = cx.tcx.hir().get(child_id) {
710 adjustments = cx.typeck_results().expr_adjustments(e);
713 Node::Local(Local { ty: Some(ty), span, .. }) if span.ctxt() == ctxt => {
714 Some(binding_ty_auto_deref_stability(cx, ty, precedence, List::empty()))
717 kind: ItemKind::Static(..) | ItemKind::Const(..),
722 | Node::TraitItem(&TraitItem {
723 kind: TraitItemKind::Const(..),
728 | Node::ImplItem(&ImplItem {
729 kind: ImplItemKind::Const(..),
733 }) if span.ctxt() == ctxt => {
734 let ty = cx.tcx.type_of(owner_id.def_id);
735 Some(ty_auto_deref_stability(cx, ty, precedence).position_for_result(cx))
739 kind: ItemKind::Fn(..),
744 | Node::TraitItem(&TraitItem {
745 kind: TraitItemKind::Fn(..),
750 | Node::ImplItem(&ImplItem {
751 kind: ImplItemKind::Fn(..),
755 }) if span.ctxt() == ctxt => {
758 .erase_late_bound_regions(cx.tcx.fn_sig(owner_id.to_def_id()).output());
759 Some(ty_auto_deref_stability(cx, output, precedence).position_for_result(cx))
762 Node::ExprField(field) if field.span.ctxt() == ctxt => match get_parent_expr_for_hir(cx, field.hir_id) {
765 kind: ExprKind::Struct(path, ..),
767 }) => variant_of_res(cx, cx.qpath_res(path, *hir_id))
768 .and_then(|variant| variant.fields.iter().find(|f| f.name == field.ident.name))
770 ty_auto_deref_stability(cx, cx.tcx.type_of(field_def.did), precedence).position_for_arg()
775 Node::Expr(parent) if parent.span.ctxt() == ctxt => match parent.kind {
776 ExprKind::Ret(_) => {
777 let owner_id = cx.tcx.hir().body_owner(cx.enclosing_body.unwrap());
780 closure_expr @ Expr {
781 kind: ExprKind::Closure(closure),
784 ) = cx.tcx.hir().get(owner_id)
786 closure_result_position(cx, closure, cx.typeck_results().expr_ty(closure_expr), precedence)
790 .erase_late_bound_regions(cx.tcx.fn_sig(cx.tcx.hir().local_def_id(owner_id)).output());
791 ty_auto_deref_stability(cx, output, precedence).position_for_result(cx)
795 ExprKind::Closure(closure) => Some(closure_result_position(
798 cx.typeck_results().expr_ty(parent),
801 ExprKind::Call(func, _) if func.hir_id == child_id => {
802 (child_id == e.hir_id).then_some(Position::Callee)
804 ExprKind::Call(func, args) => args
806 .position(|arg| arg.hir_id == child_id)
807 .zip(expr_sig(cx, func))
808 .and_then(|(i, sig)| {
809 sig.input_with_hir(i).map(|(hir_ty, ty)| match hir_ty {
810 // Type inference for closures can depend on how they're called. Only go by the explicit
812 Some(hir_ty) => binding_ty_auto_deref_stability(cx, hir_ty, precedence, ty.bound_vars()),
814 if let ty::Param(param_ty) = ty.skip_binder().kind() {
815 needless_borrow_impl_arg_position(
826 ty_auto_deref_stability(cx, cx.tcx.erase_late_bound_regions(ty), precedence)
832 ExprKind::MethodCall(_, receiver, args, _) => {
833 let id = cx.typeck_results().type_dependent_def_id(parent.hir_id).unwrap();
834 if receiver.hir_id == child_id {
835 // Check for calls to trait methods where the trait is implemented on a reference.
836 // Two cases need to be handled:
837 // * `self` methods on `&T` will never have auto-borrow
838 // * `&self` methods on `&T` can have auto-borrow, but `&self` methods on `T` will take
840 if e.hir_id != child_id {
841 return Some(Position::ReborrowStable(precedence))
842 } else if let Some(trait_id) = cx.tcx.trait_of_item(id)
843 && let arg_ty = cx.tcx.erase_regions(cx.typeck_results().expr_ty_adjusted(e))
844 && let ty::Ref(_, sub_ty, _) = *arg_ty.kind()
845 && let subs = match cx
847 .node_substs_opt(parent.hir_id)
848 .and_then(|subs| subs.get(1..))
850 Some(subs) => cx.tcx.mk_substs(subs.iter().copied()),
851 None => cx.tcx.mk_substs(std::iter::empty::<ty::subst::GenericArg<'_>>()),
852 } && let impl_ty = if cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref() {
853 // Trait methods taking `&self`
856 // Trait methods taking `self`
858 } && impl_ty.is_ref()
859 && let infcx = cx.tcx.infer_ctxt().build()
861 .type_implements_trait(trait_id, impl_ty, subs, cx.param_env)
862 .must_apply_modulo_regions()
864 return Some(Position::MethodReceiverRefImpl)
866 return Some(Position::MethodReceiver);
868 args.iter().position(|arg| arg.hir_id == child_id).map(|i| {
869 let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i + 1];
870 if let ty::Param(param_ty) = ty.kind() {
871 needless_borrow_impl_arg_position(
882 ty_auto_deref_stability(
884 cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).input(i + 1)),
891 ExprKind::Field(child, name) if child.hir_id == e.hir_id => Some(Position::FieldAccess {
893 of_union: is_union(cx.typeck_results(), child),
895 ExprKind::Unary(UnOp::Deref, child) if child.hir_id == e.hir_id => Some(Position::Deref),
896 ExprKind::Match(child, _, MatchSource::TryDesugar | MatchSource::AwaitDesugar)
897 | ExprKind::Index(child, _)
898 if child.hir_id == e.hir_id =>
900 Some(Position::Postfix)
902 _ if child_id == e.hir_id => {
903 precedence = parent.precedence().order();
911 .unwrap_or(Position::Other(precedence));
912 (position, adjustments)
915 fn is_union<'tcx>(typeck: &'tcx TypeckResults<'_>, path_expr: &'tcx Expr<'_>) -> bool {
917 .expr_ty_adjusted(path_expr)
919 .map_or(false, rustc_middle::ty::AdtDef::is_union)
922 fn closure_result_position<'tcx>(
923 cx: &LateContext<'tcx>,
924 closure: &'tcx Closure<'_>,
928 match closure.fn_decl.output {
929 FnRetTy::Return(hir_ty) => {
930 if let Some(sig) = ty_sig(cx, ty)
931 && let Some(output) = sig.output()
933 binding_ty_auto_deref_stability(cx, hir_ty, precedence, output.bound_vars())
935 Position::Other(precedence)
938 FnRetTy::DefaultReturn(_) => Position::Other(precedence),
942 // Checks the stability of auto-deref when assigned to a binding with the given explicit type.
945 // let x = Box::new(Box::new(0u32));
946 // let y1: &Box<_> = x.deref();
947 // let y2: &Box<_> = &x;
949 // Here `y1` and `y2` would resolve to different types, so the type `&Box<_>` is not stable when
950 // switching to auto-dereferencing.
951 fn binding_ty_auto_deref_stability<'tcx>(
952 cx: &LateContext<'tcx>,
953 ty: &'tcx hir::Ty<'_>,
955 binder_args: &'tcx List<BoundVariableKind>,
957 let TyKind::Rptr(_, ty) = &ty.kind else {
958 return Position::Other(precedence);
963 break match ty.ty.kind {
964 TyKind::Rptr(_, ref ref_ty) => {
969 QPath::TypeRelative(_, path)
973 segments: [.., path], ..
977 if let Some(args) = path.args
978 && args.args.iter().any(|arg| match arg {
979 GenericArg::Infer(_) => true,
980 GenericArg::Type(ty) => ty_contains_infer(ty),
984 Position::ReborrowStable(precedence)
986 Position::DerefStable(
989 .erase_late_bound_regions(Binder::bind_with_vars(
990 cx.typeck_results().node_type(ty.ty.hir_id),
993 .is_sized(cx.tcx, cx.param_env.without_caller_bounds()),
997 TyKind::Slice(_) => Position::DerefStable(precedence, false),
998 TyKind::Array(..) | TyKind::Ptr(_) | TyKind::BareFn(_) => Position::DerefStable(precedence, true),
1001 | TyKind::Path(_) => Position::DerefStable(
1004 .erase_late_bound_regions(Binder::bind_with_vars(
1005 cx.typeck_results().node_type(ty.ty.hir_id),
1008 .is_sized(cx.tcx, cx.param_env.without_caller_bounds()),
1010 TyKind::OpaqueDef(..) | TyKind::Infer | TyKind::Typeof(..) | TyKind::TraitObject(..) | TyKind::Err => {
1011 Position::ReborrowStable(precedence)
1017 // Checks whether a type is inferred at some point.
1018 // e.g. `_`, `Box<_>`, `[_]`
1019 fn ty_contains_infer(ty: &hir::Ty<'_>) -> bool {
1021 impl Visitor<'_> for V {
1022 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1026 TyKind::OpaqueDef(..) | TyKind::Infer | TyKind::Typeof(_) | TyKind::Err
1035 fn visit_generic_arg(&mut self, arg: &GenericArg<'_>) {
1036 if self.0 || matches!(arg, GenericArg::Infer(_)) {
1038 } else if let GenericArg::Type(ty) = arg {
1043 let mut v = V(false);
1049 // * child is an expression of the form `&e` in an argument position requiring an `impl Trait`
1050 // * `e`'s type implements `Trait` and is copyable
1051 // If the conditions are met, returns `Some(Position::ImplArg(..))`; otherwise, returns `None`.
1052 // The "is copyable" condition is to avoid the case where removing the `&` means `e` would have to
1053 // be moved, but it cannot be.
1054 #[expect(clippy::too_many_arguments)]
1055 fn needless_borrow_impl_arg_position<'tcx>(
1056 cx: &LateContext<'tcx>,
1057 possible_borrowers: &mut Vec<(LocalDefId, PossibleBorrowerMap<'tcx, 'tcx>)>,
1058 parent: &Expr<'tcx>,
1061 mut expr: &Expr<'tcx>,
1063 msrv: Option<RustcVersion>,
1065 let destruct_trait_def_id = cx.tcx.lang_items().destruct_trait();
1066 let sized_trait_def_id = cx.tcx.lang_items().sized_trait();
1068 let Some(callee_def_id) = fn_def_id(cx, parent) else { return Position::Other(precedence) };
1069 let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder();
1070 let substs_with_expr_ty = cx
1072 .node_substs(if let ExprKind::Call(callee, _) = parent.kind {
1078 let predicates = cx.tcx.param_env(callee_def_id).caller_bounds();
1079 let projection_predicates = predicates
1081 .filter_map(|predicate| {
1082 if let PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1083 Some(projection_predicate)
1088 .collect::<Vec<_>>();
1090 let mut trait_with_ref_mut_self_method = false;
1092 // If no traits were found, or only the `Destruct`, `Sized`, or `Any` traits were found, return.
1095 .filter_map(|predicate| {
1096 if let PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder()
1097 && trait_predicate.trait_ref.self_ty() == param_ty.to_ty(cx.tcx)
1099 Some(trait_predicate.trait_ref.def_id)
1104 .inspect(|trait_def_id| {
1105 trait_with_ref_mut_self_method |= has_ref_mut_self_method(cx, *trait_def_id);
1107 .all(|trait_def_id| {
1108 Some(trait_def_id) == destruct_trait_def_id
1109 || Some(trait_def_id) == sized_trait_def_id
1110 || cx.tcx.is_diagnostic_item(sym::Any, trait_def_id)
1113 return Position::Other(precedence);
1116 // `substs_with_referent_ty` can be constructed outside of `check_referent` because the same
1117 // elements are modified each time `check_referent` is called.
1118 let mut substs_with_referent_ty = substs_with_expr_ty.to_vec();
1120 let mut check_reference_and_referent = |reference, referent| {
1121 let referent_ty = cx.typeck_results().expr_ty(referent);
1123 if !is_copy(cx, referent_ty)
1124 && (referent_ty.has_significant_drop(cx.tcx, cx.param_env)
1125 || !referent_used_exactly_once(cx, possible_borrowers, reference))
1130 // https://github.com/rust-lang/rust-clippy/pull/9136#pullrequestreview-1037379321
1131 if trait_with_ref_mut_self_method && !matches!(referent_ty.kind(), ty::Ref(_, _, Mutability::Mut)) {
1141 &projection_predicates,
1142 &mut substs_with_referent_ty,
1147 predicates.iter().all(|predicate| {
1148 if let PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder()
1149 && cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_predicate.trait_ref.def_id)
1150 && let ty::Param(param_ty) = trait_predicate.self_ty().kind()
1151 && let GenericArgKind::Type(ty) = substs_with_referent_ty[param_ty.index as usize].unpack()
1153 && !meets_msrv(msrv, msrvs::ARRAY_INTO_ITERATOR)
1158 let predicate = EarlyBinder(predicate).subst(cx.tcx, &substs_with_referent_ty);
1159 let obligation = Obligation::new(ObligationCause::dummy(), cx.param_env, predicate);
1160 let infcx = cx.tcx.infer_ctxt().build();
1161 infcx.predicate_must_hold_modulo_regions(&obligation)
1165 let mut needless_borrow = false;
1166 while let ExprKind::AddrOf(_, _, referent) = expr.kind {
1167 if !check_reference_and_referent(expr, referent) {
1171 needless_borrow = true;
1174 if needless_borrow {
1175 Position::ImplArg(expr.hir_id)
1177 Position::Other(precedence)
1181 fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool {
1183 .associated_items(trait_def_id)
1184 .in_definition_order()
1186 if assoc_item.fn_has_self_parameter {
1187 let self_ty = cx.tcx.fn_sig(assoc_item.def_id).skip_binder().inputs()[0];
1188 matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Mut))
1195 fn referent_used_exactly_once<'tcx>(
1196 cx: &LateContext<'tcx>,
1197 possible_borrowers: &mut Vec<(LocalDefId, PossibleBorrowerMap<'tcx, 'tcx>)>,
1198 reference: &Expr<'tcx>,
1200 let mir = enclosing_mir(cx.tcx, reference.hir_id);
1201 if let Some(local) = expr_local(cx.tcx, reference)
1202 && let [location] = *local_assignments(mir, local).as_slice()
1203 && let Some(statement) = mir.basic_blocks[location.block].statements.get(location.statement_index)
1204 && let StatementKind::Assign(box (_, Rvalue::Ref(_, _, place))) = statement.kind
1205 && !place.has_deref()
1207 let body_owner_local_def_id = cx.tcx.hir().enclosing_body_owner(reference.hir_id);
1208 if possible_borrowers
1210 .map_or(true, |&(local_def_id, _)| local_def_id != body_owner_local_def_id)
1212 possible_borrowers.push((body_owner_local_def_id, PossibleBorrowerMap::new(cx, mir)));
1214 let possible_borrower = &mut possible_borrowers.last_mut().unwrap().1;
1215 // If `only_borrowers` were used here, the `copyable_iterator::warn` test would fail. The reason is
1216 // that `PossibleBorrowerVisitor::visit_terminator` considers `place.local` a possible borrower of
1217 // itself. See the comment in that method for an explanation as to why.
1218 possible_borrower.bounded_borrowers(&[local], &[local, place.local], place.local, location)
1219 && used_exactly_once(mir, place.local).unwrap_or(false)
1225 // Iteratively replaces `param_ty` with `new_ty` in `substs`, and similarly for each resulting
1226 // projected type that is a type parameter. Returns `false` if replacing the types would have an
1227 // effect on the function signature beyond substituting `new_ty` for `param_ty`.
1228 // See: https://github.com/rust-lang/rust-clippy/pull/9136#discussion_r927212757
1229 fn replace_types<'tcx>(
1230 cx: &LateContext<'tcx>,
1233 fn_sig: FnSig<'tcx>,
1235 projection_predicates: &[ProjectionPredicate<'tcx>],
1236 substs: &mut [ty::GenericArg<'tcx>],
1238 let mut replaced = BitSet::new_empty(substs.len());
1240 let mut deque = VecDeque::with_capacity(substs.len());
1241 deque.push_back((param_ty, new_ty));
1243 while let Some((param_ty, new_ty)) = deque.pop_front() {
1244 // If `replaced.is_empty()`, then `param_ty` and `new_ty` are those initially passed in.
1249 .all(|(i, ty)| (replaced.is_empty() && i == arg_index) || !ty.contains(param_ty.to_ty(cx.tcx)))
1254 substs[param_ty.index as usize] = ty::GenericArg::from(new_ty);
1256 // The `replaced.insert(...)` check provides some protection against infinite loops.
1257 if replaced.insert(param_ty.index) {
1258 for projection_predicate in projection_predicates {
1259 if projection_predicate.projection_ty.self_ty() == param_ty.to_ty(cx.tcx)
1260 && let Some(term_ty) = projection_predicate.term.ty()
1261 && let ty::Param(term_param_ty) = term_ty.kind()
1263 let item_def_id = projection_predicate.projection_ty.item_def_id;
1264 let assoc_item = cx.tcx.associated_item(item_def_id);
1265 let projection = cx.tcx
1266 .mk_projection(assoc_item.def_id, cx.tcx.mk_substs_trait(new_ty, &[]));
1268 if let Ok(projected_ty) = cx.tcx.try_normalize_erasing_regions(cx.param_env, projection)
1269 && substs[term_param_ty.index as usize] != ty::GenericArg::from(projected_ty)
1271 deque.push_back((*term_param_ty, projected_ty));
1281 struct TyPosition<'tcx> {
1283 ty: Option<Ty<'tcx>>,
1285 impl From<Position> for TyPosition<'_> {
1286 fn from(position: Position) -> Self {
1287 Self { position, ty: None }
1290 impl<'tcx> TyPosition<'tcx> {
1291 fn new_deref_stable_for_result(precedence: i8, ty: Ty<'tcx>) -> Self {
1293 position: Position::ReborrowStable(precedence),
1297 fn position_for_result(self, cx: &LateContext<'tcx>) -> Position {
1298 match (self.position, self.ty) {
1299 (Position::ReborrowStable(precedence), Some(ty)) => {
1300 Position::DerefStable(precedence, ty.is_sized(cx.tcx, cx.param_env))
1302 (position, _) => position,
1305 fn position_for_arg(self) -> Position {
1310 // Checks whether a type is stable when switching to auto dereferencing,
1311 fn ty_auto_deref_stability<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, precedence: i8) -> TyPosition<'tcx> {
1312 let ty::Ref(_, mut ty, _) = *ty.kind() else {
1313 return Position::Other(precedence).into();
1317 break match *ty.kind() {
1318 ty::Ref(_, ref_ty, _) => {
1322 ty::Param(_) => TyPosition::new_deref_stable_for_result(precedence, ty),
1323 ty::Infer(_) | ty::Error(_) | ty::Bound(..) | ty::Opaque(..) | ty::Placeholder(_) | ty::Dynamic(..) => {
1324 Position::ReborrowStable(precedence).into()
1326 ty::Adt(..) if ty.has_placeholders() || ty.has_opaque_types() => {
1327 Position::ReborrowStable(precedence).into()
1329 ty::Adt(_, substs) if substs.has_non_region_param() => {
1330 TyPosition::new_deref_stable_for_result(precedence, ty)
1339 | ty::FnPtr(_) => Position::DerefStable(precedence, true).into(),
1340 ty::Str | ty::Slice(..) => Position::DerefStable(precedence, false).into(),
1345 | ty::GeneratorWitness(..)
1349 | ty::Projection(_) => Position::DerefStable(
1351 ty.is_sized(cx.tcx, cx.param_env.without_caller_bounds()),
1358 fn ty_contains_field(ty: Ty<'_>, name: Symbol) -> bool {
1359 if let ty::Adt(adt, _) = *ty.kind() {
1360 adt.is_struct() && adt.all_fields().any(|f| f.name == name)
1366 #[expect(clippy::needless_pass_by_value, clippy::too_many_lines)]
1367 fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data: StateData) {
1369 State::DerefMethod {
1374 let mut app = Applicability::MachineApplicable;
1375 let (expr_str, expr_is_macro_call) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
1376 let ty = cx.typeck_results().expr_ty(expr);
1377 let (_, ref_count) = peel_mid_ty_refs(ty);
1378 let deref_str = if ty_changed_count >= ref_count && ref_count != 0 {
1379 // a deref call changing &T -> &U requires two deref operators the first time
1380 // this occurs. One to remove the reference, a second to call the deref impl.
1381 "*".repeat(ty_changed_count + 1)
1383 "*".repeat(ty_changed_count)
1385 let addr_of_str = if ty_changed_count < ref_count {
1386 // Check if a reborrow from &mut T -> &T is required.
1387 if target_mut == Mutability::Not && matches!(ty.kind(), ty::Ref(_, _, Mutability::Mut)) {
1392 } else if target_mut == Mutability::Mut {
1398 let expr_str = if !expr_is_macro_call && is_final_ufcs && expr.precedence().order() < PREC_PREFIX {
1399 format!("({expr_str})")
1401 expr_str.into_owned()
1406 EXPLICIT_DEREF_METHODS,
1409 Mutability::Not => "explicit `deref` method call",
1410 Mutability::Mut => "explicit `deref_mut` method call",
1413 format!("{addr_of_str}{deref_str}{expr_str}"),
1417 State::DerefedBorrow(state) => {
1418 let mut app = Applicability::MachineApplicable;
1419 let snip_expr = state.snip_expr.map_or(expr, |hir_id| cx.tcx.hir().expect_expr(hir_id));
1420 let (snip, snip_is_macro) = snippet_with_context(cx, snip_expr.span, data.span.ctxt(), "..", &mut app);
1421 span_lint_hir_and_then(cx, NEEDLESS_BORROW, data.hir_id, data.span, state.msg, |diag| {
1422 let calls_field = matches!(expr.kind, ExprKind::Field(..)) && matches!(data.position, Position::Callee);
1423 let sugg = if !snip_is_macro
1424 && !has_enclosing_paren(&snip)
1425 && (expr.precedence().order() < data.position.precedence() || calls_field)
1431 diag.span_suggestion(data.span, "change this to", sugg, app);
1434 State::ExplicitDeref { mutability } => {
1438 | ExprKind::ConstBlock(_)
1440 | ExprKind::Loop(..)
1441 | ExprKind::Match(..)
1442 ) && matches!(data.position, Position::DerefStable(_, true))
1444 // Rustc bug: auto deref doesn't work on block expression when targeting sized types.
1448 let (prefix, precedence) = if let Some(mutability) = mutability
1449 && !cx.typeck_results().expr_ty(expr).is_ref()
1451 let prefix = match mutability {
1452 Mutability::Not => "&",
1453 Mutability::Mut => "&mut ",
1457 ("", data.position.precedence())
1459 span_lint_hir_and_then(
1461 EXPLICIT_AUTO_DEREF,
1464 "deref which would be done by auto-deref",
1466 let mut app = Applicability::MachineApplicable;
1467 let (snip, snip_is_macro) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
1469 if !snip_is_macro && expr.precedence().order() < precedence && !has_enclosing_paren(&snip) {
1470 format!("{prefix}({snip})")
1472 format!("{prefix}{snip}")
1474 diag.span_suggestion(data.span, "try this", sugg, app);
1478 State::ExplicitDerefField { .. } => {
1482 | ExprKind::ConstBlock(_)
1484 | ExprKind::Loop(..)
1485 | ExprKind::Match(..)
1486 ) && matches!(data.position, Position::DerefStable(_, true))
1488 // Rustc bug: auto deref doesn't work on block expression when targeting sized types.
1492 span_lint_hir_and_then(
1494 EXPLICIT_AUTO_DEREF,
1497 "deref which would be done by auto-deref",
1499 let mut app = Applicability::MachineApplicable;
1500 let snip = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app).0;
1501 diag.span_suggestion(data.span, "try this", snip.into_owned(), app);
1505 State::Borrow { .. } | State::Reborrow { .. } => (),
1509 impl<'tcx> Dereferencing<'tcx> {
1510 fn check_local_usage(&mut self, cx: &LateContext<'tcx>, e: &Expr<'tcx>, local: HirId) {
1511 if let Some(outer_pat) = self.ref_locals.get_mut(&local) {
1512 if let Some(pat) = outer_pat {
1513 // Check for auto-deref
1515 cx.typeck_results().expr_adjustments(e),
1518 kind: Adjust::Deref(_),
1522 kind: Adjust::Deref(_),
1528 match get_parent_expr(cx, e) {
1529 // Field accesses are the same no matter the number of references.
1531 kind: ExprKind::Field(..),
1536 kind: ExprKind::Unary(UnOp::Deref, _),
1538 }) if !span.from_expansion() => {
1539 // Remove explicit deref.
1540 let snip = snippet_with_context(cx, e.span, span.ctxt(), "..", &mut pat.app).0;
1541 pat.replacements.push((span, snip.into()));
1543 Some(parent) if !parent.span.from_expansion() => {
1544 // Double reference might be needed at this point.
1545 if parent.precedence().order() == PREC_POSTFIX {
1546 // Parentheses would be needed here, don't lint.
1549 pat.always_deref = false;
1550 let snip = snippet_with_context(cx, e.span, parent.span.ctxt(), "..", &mut pat.app).0;
1551 pat.replacements.push((e.span, format!("&{snip}")));
1554 _ if !e.span.from_expansion() => {
1555 // Double reference might be needed at this point.
1556 pat.always_deref = false;
1557 let snip = snippet_with_applicability(cx, e.span, "..", &mut pat.app);
1558 pat.replacements.push((e.span, format!("&{snip}")));
1560 // Edge case for macros. The span of the identifier will usually match the context of the
1561 // binding, but not if the identifier was created in a macro. e.g. `concat_idents` and proc
1563 _ => *outer_pat = None,