1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_hir_and_then};
2 use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
3 use clippy_utils::sugg::has_enclosing_paren;
4 use clippy_utils::ty::{contains_ty, expr_sig, is_copy, peel_mid_ty_refs, ty_sig, variant_of_res};
5 use clippy_utils::{fn_def_id, get_parent_expr, is_lint_allowed, meets_msrv, msrvs, path_to_local, walk_to_expr_usage};
6 use rustc_ast::util::parser::{PREC_POSTFIX, PREC_PREFIX};
7 use rustc_data_structures::fx::FxIndexMap;
8 use rustc_errors::Applicability;
9 use rustc_hir::intravisit::{walk_ty, Visitor};
11 self as hir, def_id::DefId, BindingAnnotation, Body, BodyId, BorrowKind, Closure, Expr, ExprKind, FnRetTy,
12 GenericArg, HirId, ImplItem, ImplItemKind, Item, ItemKind, Local, MatchSource, Mutability, Node, Pat, PatKind,
13 Path, QPath, TraitItem, TraitItemKind, TyKind, UnOp,
15 use rustc_index::bit_set::BitSet;
16 use rustc_infer::infer::TyCtxtInferExt;
17 use rustc_lint::{LateContext, LateLintPass};
18 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
19 use rustc_middle::ty::{
20 self, subst::Subst, Binder, BoundVariableKind, EarlyBinder, FnSig, GenericArgKind, List, ParamTy, PredicateKind,
21 ProjectionPredicate, Ty, TyCtxt, TypeVisitable, TypeckResults,
23 use rustc_semver::RustcVersion;
24 use rustc_session::{declare_tool_lint, impl_lint_pass};
25 use rustc_span::{symbol::sym, Span, Symbol, DUMMY_SP};
26 use rustc_trait_selection::infer::InferCtxtExt as _;
27 use rustc_trait_selection::traits::{query::evaluate_obligation::InferCtxtExt as _, Obligation, ObligationCause};
28 use std::collections::VecDeque;
30 declare_clippy_lint! {
32 /// Checks for explicit `deref()` or `deref_mut()` method calls.
34 /// ### Why is this bad?
35 /// Dereferencing by `&*x` or `&mut *x` is clearer and more concise,
36 /// when not part of a method chain.
40 /// use std::ops::Deref;
41 /// let a: &mut String = &mut String::from("foo");
42 /// let b: &str = a.deref();
47 /// let a: &mut String = &mut String::from("foo");
51 /// This lint excludes:
53 /// let _ = d.unwrap().deref();
55 #[clippy::version = "1.44.0"]
56 pub EXPLICIT_DEREF_METHODS,
58 "Explicit use of deref or deref_mut method while not in a method chain."
61 declare_clippy_lint! {
63 /// Checks for address of operations (`&`) that are going to
64 /// be dereferenced immediately by the compiler.
66 /// ### Why is this bad?
67 /// Suggests that the receiver of the expression borrows
72 /// fn fun(_a: &i32) {}
74 /// let x: &i32 = &&&&&&5;
80 /// # fn fun(_a: &i32) {}
84 #[clippy::version = "pre 1.29.0"]
87 "taking a reference that is going to be automatically dereferenced"
90 declare_clippy_lint! {
92 /// Checks for `ref` bindings which create a reference to a reference.
94 /// ### Why is this bad?
95 /// The address-of operator at the use site is clearer about the need for a reference.
100 /// if let Some(ref x) = x {
107 /// let x = Some("");
108 /// if let Some(x) = x {
112 #[clippy::version = "1.54.0"]
113 pub REF_BINDING_TO_REFERENCE,
115 "`ref` binding to a reference"
118 declare_clippy_lint! {
120 /// Checks for dereferencing expressions which would be covered by auto-deref.
122 /// ### Why is this bad?
123 /// This unnecessarily complicates the code.
127 /// let x = String::new();
128 /// let y: &str = &*x;
132 /// let x = String::new();
133 /// let y: &str = &x;
135 #[clippy::version = "1.60.0"]
136 pub EXPLICIT_AUTO_DEREF,
138 "dereferencing when the compiler would automatically dereference"
141 impl_lint_pass!(Dereferencing => [
142 EXPLICIT_DEREF_METHODS,
144 REF_BINDING_TO_REFERENCE,
149 pub struct Dereferencing {
150 state: Option<(State, StateData)>,
152 // While parsing a `deref` method call in ufcs form, the path to the function is itself an
153 // expression. This is to store the id of that expression so it can be skipped when
154 // `check_expr` is called for it.
155 skip_expr: Option<HirId>,
157 /// The body the first local was found in. Used to emit lints when the traversal of the body has
158 /// been finished. Note we can't lint at the end of every body as they can be nested within each
160 current_body: Option<BodyId>,
162 /// The list of locals currently being checked by the lint.
163 /// If the value is `None`, then the binding has been seen as a ref pattern, but is not linted.
164 /// This is needed for or patterns where one of the branches can be linted, but another can not
167 /// e.g. `m!(x) | Foo::Bar(ref x)`
168 ref_locals: FxIndexMap<HirId, Option<RefPat>>,
170 // `IntoIterator` for arrays requires Rust 1.53.
171 msrv: Option<RustcVersion>,
176 pub fn new(msrv: Option<RustcVersion>) -> Self {
179 ..Dereferencing::default()
185 /// Span of the top level expression
191 struct DerefedBorrow {
194 snip_expr: Option<HirId>,
198 // Any number of deref method calls.
200 // The number of calls in a sequence which changed the referenced type
201 ty_changed_count: usize,
203 /// The required mutability
204 target_mut: Mutability,
206 DerefedBorrow(DerefedBorrow),
208 mutability: Option<Mutability>,
214 mutability: Mutability,
217 mutability: Mutability,
221 // A reference operation considered by this lint pass
229 /// Whether every usage of the binding is dereferenced.
231 /// The spans of all the ref bindings for this local.
233 /// The applicability of this suggestion.
235 /// All the replacements which need to be made.
236 replacements: Vec<(Span, String)>,
237 /// The [`HirId`] that the lint should be emitted at.
241 impl<'tcx> LateLintPass<'tcx> for Dereferencing {
242 #[expect(clippy::too_many_lines)]
243 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
244 // Skip path expressions from deref calls. e.g. `Deref::deref(e)`
245 if Some(expr.hir_id) == self.skip_expr.take() {
249 if let Some(local) = path_to_local(expr) {
250 self.check_local_usage(cx, expr, local);
253 // Stop processing sub expressions when a macro call is seen
254 if expr.span.from_expansion() {
255 if let Some((state, data)) = self.state.take() {
256 report(cx, expr, state, data);
261 let typeck = cx.typeck_results();
262 let (kind, sub_expr) = if let Some(x) = try_parse_ref_op(cx.tcx, typeck, expr) {
265 // The whole chain of reference operations has been seen
266 if let Some((state, data)) = self.state.take() {
267 report(cx, expr, state, data);
272 match (self.state.take(), kind) {
274 let expr_ty = typeck.expr_ty(expr);
275 let (position, adjustments) = walk_parents(cx, expr, self.msrv);
279 if let Position::FieldAccess(name) = position
280 && !ty_contains_field(typeck.expr_ty(sub_expr), name)
283 State::ExplicitDerefField { name },
284 StateData { span: expr.span, hir_id: expr.hir_id, position },
286 } else if position.is_deref_stable() {
288 State::ExplicitDeref { mutability: None },
289 StateData { span: expr.span, hir_id: expr.hir_id, position },
293 RefOp::Method(target_mut)
294 if !is_lint_allowed(cx, EXPLICIT_DEREF_METHODS, expr.hir_id)
295 && position.lint_explicit_deref() =>
299 ty_changed_count: if deref_method_same_type(expr_ty, typeck.expr_ty(sub_expr)) {
304 is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
314 RefOp::AddrOf(mutability) => {
315 // Find the number of times the borrow is auto-derefed.
316 let mut iter = adjustments.iter();
317 let mut deref_count = 0usize;
318 let next_adjust = loop {
321 if !matches!(adjust.kind, Adjust::Deref(_)) {
323 } else if !adjust.target.is_ref() {
333 // Determine the required number of references before any can be removed. In all cases the
334 // reference made by the current expression will be removed. After that there are four cases to
337 // 1. Auto-borrow will trigger in the current position, so no further references are required.
338 // 2. Auto-deref ends at a reference, or the underlying type, so one extra needs to be left to
339 // handle the automatically inserted re-borrow.
340 // 3. Auto-deref hits a user-defined `Deref` impl, so at least one reference needs to exist to
342 // 4. If the chain of non-user-defined derefs ends with a mutable re-borrow, and re-borrow
343 // adjustments will not be inserted automatically, then leave one further reference to avoid
344 // moving a mutable borrow.
346 // fn foo<T>(x: &mut Option<&mut T>, y: &mut T) {
348 // // Removing the borrow will cause `x` to be moved
349 // Some(x) => &mut *x,
354 "this expression creates a reference which is immediately dereferenced by the compiler";
355 let borrow_msg = "this expression borrows a value the compiler would automatically borrow";
356 let impl_msg = "the borrowed expression implements the required traits";
358 let (required_refs, msg, snip_expr) = if position.can_auto_borrow() {
359 (1, if deref_count == 1 { borrow_msg } else { deref_msg }, None)
360 } else if let Position::ImplArg(hir_id) = position {
361 (0, impl_msg, Some(hir_id))
362 } else if let Some(&Adjust::Borrow(AutoBorrow::Ref(_, mutability))) =
363 next_adjust.map(|a| &a.kind)
365 if matches!(mutability, AutoBorrowMutability::Mut { .. }) && !position.is_reborrow_stable()
375 if deref_count >= required_refs {
377 State::DerefedBorrow(DerefedBorrow {
378 // One of the required refs is for the current borrow expression, the remaining ones
379 // can't be removed without breaking the code. See earlier comment.
380 count: deref_count - required_refs,
384 StateData { span: expr.span, hir_id: expr.hir_id, position },
386 } else if position.is_deref_stable()
387 // Auto-deref doesn't combine with other adjustments
388 && next_adjust.map_or(true, |a| matches!(a.kind, Adjust::Deref(_) | Adjust::Borrow(_)))
389 && iter.all(|a| matches!(a.kind, Adjust::Deref(_) | Adjust::Borrow(_)))
392 State::Borrow { mutability },
401 RefOp::Method(..) => (),
417 ty_changed_count: if deref_method_same_type(typeck.expr_ty(expr), typeck.expr_ty(sub_expr)) {
422 is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
428 (Some((State::DerefedBorrow(state), data)), RefOp::AddrOf(_)) if state.count != 0 => {
430 State::DerefedBorrow(DerefedBorrow {
431 count: state.count - 1,
437 (Some((State::DerefedBorrow(state), data)), RefOp::AddrOf(mutability)) => {
438 let position = data.position;
439 report(cx, expr, State::DerefedBorrow(state), data);
440 if position.is_deref_stable() {
442 State::Borrow { mutability },
451 (Some((State::DerefedBorrow(state), data)), RefOp::Deref) => {
452 let position = data.position;
453 report(cx, expr, State::DerefedBorrow(state), data);
454 if let Position::FieldAccess(name) = position
455 && !ty_contains_field(typeck.expr_ty(sub_expr), name)
458 State::ExplicitDerefField { name },
459 StateData { span: expr.span, hir_id: expr.hir_id, position },
461 } else if position.is_deref_stable() {
463 State::ExplicitDeref { mutability: None },
464 StateData { span: expr.span, hir_id: expr.hir_id, position },
469 (Some((State::Borrow { mutability }, data)), RefOp::Deref) => {
470 if typeck.expr_ty(sub_expr).is_ref() {
471 self.state = Some((State::Reborrow { mutability }, data));
474 State::ExplicitDeref {
475 mutability: Some(mutability),
481 (Some((State::Reborrow { mutability }, data)), RefOp::Deref) => {
483 State::ExplicitDeref {
484 mutability: Some(mutability),
489 (state @ Some((State::ExplicitDeref { .. }, _)), RefOp::Deref) => {
492 (Some((State::ExplicitDerefField { name }, data)), RefOp::Deref)
493 if !ty_contains_field(typeck.expr_ty(sub_expr), name) =>
495 self.state = Some((State::ExplicitDerefField { name }, data));
498 (Some((state, data)), _) => report(cx, expr, state, data),
502 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
503 if let PatKind::Binding(BindingAnnotation::Ref, id, name, _) = pat.kind {
504 if let Some(opt_prev_pat) = self.ref_locals.get_mut(&id) {
505 // This binding id has been seen before. Add this pattern to the list of changes.
506 if let Some(prev_pat) = opt_prev_pat {
507 if pat.span.from_expansion() {
508 // Doesn't match the context of the previous pattern. Can't lint here.
509 *opt_prev_pat = None;
511 prev_pat.spans.push(pat.span);
512 prev_pat.replacements.push((
514 snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut prev_pat.app)
524 if !pat.span.from_expansion();
525 if let ty::Ref(_, tam, _) = *cx.typeck_results().pat_ty(pat).kind();
526 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
527 if let ty::Ref(_, _, Mutability::Not) = *tam.kind();
529 let mut app = Applicability::MachineApplicable;
530 let snip = snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut app).0;
531 self.current_body = self.current_body.or(cx.enclosing_body);
532 self.ref_locals.insert(
536 spans: vec![pat.span],
538 replacements: vec![(pat.span, snip.into())],
547 fn check_body_post(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
548 if Some(body.id()) == self.current_body {
549 for pat in self.ref_locals.drain(..).filter_map(|(_, x)| x) {
550 let replacements = pat.replacements;
552 let lint = if pat.always_deref {
555 REF_BINDING_TO_REFERENCE
557 span_lint_hir_and_then(
562 "this pattern creates a reference to a reference",
564 diag.multipart_suggestion("try this", replacements, app);
568 self.current_body = None;
572 extract_msrv_attr!(LateContext);
575 fn try_parse_ref_op<'tcx>(
577 typeck: &'tcx TypeckResults<'_>,
578 expr: &'tcx Expr<'_>,
579 ) -> Option<(RefOp, &'tcx Expr<'tcx>)> {
580 let (def_id, arg) = match expr.kind {
581 ExprKind::MethodCall(_, [arg], _) => (typeck.type_dependent_def_id(expr.hir_id)?, arg),
584 kind: ExprKind::Path(path),
589 ) => (typeck.qpath_res(path, *hir_id).opt_def_id()?, arg),
590 ExprKind::Unary(UnOp::Deref, sub_expr) if !typeck.expr_ty(sub_expr).is_unsafe_ptr() => {
591 return Some((RefOp::Deref, sub_expr));
593 ExprKind::AddrOf(BorrowKind::Ref, mutability, sub_expr) => return Some((RefOp::AddrOf(mutability), sub_expr)),
596 if tcx.is_diagnostic_item(sym::deref_method, def_id) {
597 Some((RefOp::Method(Mutability::Not), arg))
598 } else if tcx.trait_of_item(def_id)? == tcx.lang_items().deref_mut_trait()? {
599 Some((RefOp::Method(Mutability::Mut), arg))
605 // Checks whether the type for a deref call actually changed the type, not just the mutability of
607 fn deref_method_same_type<'tcx>(result_ty: Ty<'tcx>, arg_ty: Ty<'tcx>) -> bool {
608 match (result_ty.kind(), arg_ty.kind()) {
609 (ty::Ref(_, result_ty, _), ty::Ref(_, arg_ty, _)) => result_ty == arg_ty,
611 // The result type for a deref method is always a reference
612 // Not matching the previous pattern means the argument type is not a reference
613 // This means that the type did change
618 /// The position of an expression relative to it's parent.
619 #[derive(Clone, Copy)]
622 /// The method is defined on a reference type. e.g. `impl Foo for &T`
623 MethodReceiverRefImpl,
629 /// Any other location which will trigger auto-deref to a specific time.
630 /// Contains the precedence of the parent expression and whether the target type is sized.
631 DerefStable(i8, bool),
632 /// Any other location which will trigger auto-reborrowing.
633 /// Contains the precedence of the parent expression.
635 /// Contains the precedence of the parent expression.
639 fn is_deref_stable(self) -> bool {
640 matches!(self, Self::DerefStable(..))
643 fn is_reborrow_stable(self) -> bool {
644 matches!(self, Self::DerefStable(..) | Self::ReborrowStable(_))
647 fn can_auto_borrow(self) -> bool {
648 matches!(self, Self::MethodReceiver | Self::FieldAccess(_) | Self::Callee)
651 fn lint_explicit_deref(self) -> bool {
652 matches!(self, Self::Other(_) | Self::DerefStable(..) | Self::ReborrowStable(_))
655 fn precedence(self) -> i8 {
658 | Self::MethodReceiverRefImpl
660 | Self::FieldAccess(_)
661 | Self::Postfix => PREC_POSTFIX,
662 Self::ImplArg(_) | Self::Deref => PREC_PREFIX,
663 Self::DerefStable(p, _) | Self::ReborrowStable(p) | Self::Other(p) => p,
668 /// Walks up the parent expressions attempting to determine both how stable the auto-deref result
669 /// is, and which adjustments will be applied to it. Note this will not consider auto-borrow
670 /// locations as those follow different rules.
671 #[expect(clippy::too_many_lines)]
672 fn walk_parents<'tcx>(
673 cx: &LateContext<'tcx>,
675 msrv: Option<RustcVersion>,
676 ) -> (Position, &'tcx [Adjustment<'tcx>]) {
677 let mut adjustments = [].as_slice();
678 let mut precedence = 0i8;
679 let ctxt = e.span.ctxt();
680 let position = walk_to_expr_usage(cx, e, &mut |parent, child_id| {
681 // LocalTableInContext returns the wrong lifetime, so go use `expr_adjustments` instead.
682 if adjustments.is_empty() && let Node::Expr(e) = cx.tcx.hir().get(child_id) {
683 adjustments = cx.typeck_results().expr_adjustments(e);
686 Node::Local(Local { ty: Some(ty), span, .. }) if span.ctxt() == ctxt => {
687 Some(binding_ty_auto_deref_stability(cx, ty, precedence, List::empty()))
690 kind: ItemKind::Static(..) | ItemKind::Const(..),
695 | Node::TraitItem(&TraitItem {
696 kind: TraitItemKind::Const(..),
701 | Node::ImplItem(&ImplItem {
702 kind: ImplItemKind::Const(..),
706 }) if span.ctxt() == ctxt => {
707 let ty = cx.tcx.type_of(def_id);
708 Some(ty_auto_deref_stability(cx, ty, precedence).position_for_result(cx))
712 kind: ItemKind::Fn(..),
717 | Node::TraitItem(&TraitItem {
718 kind: TraitItemKind::Fn(..),
723 | Node::ImplItem(&ImplItem {
724 kind: ImplItemKind::Fn(..),
728 }) if span.ctxt() == ctxt => {
731 .erase_late_bound_regions(cx.tcx.fn_sig(def_id.to_def_id()).output());
732 Some(ty_auto_deref_stability(cx, output, precedence).position_for_result(cx))
735 Node::Expr(parent) if parent.span.ctxt() == ctxt => match parent.kind {
736 ExprKind::Ret(_) => {
737 let owner_id = cx.tcx.hir().body_owner(cx.enclosing_body.unwrap());
740 closure_expr @ Expr {
741 kind: ExprKind::Closure(closure),
744 ) = cx.tcx.hir().get(owner_id)
746 closure_result_position(cx, closure, cx.typeck_results().expr_ty(closure_expr), precedence)
750 .erase_late_bound_regions(cx.tcx.fn_sig(cx.tcx.hir().local_def_id(owner_id)).output());
751 ty_auto_deref_stability(cx, output, precedence).position_for_result(cx)
755 ExprKind::Closure(closure) => Some(closure_result_position(
758 cx.typeck_results().expr_ty(parent),
761 ExprKind::Call(func, _) if func.hir_id == child_id => {
762 (child_id == e.hir_id).then_some(Position::Callee)
764 ExprKind::Call(func, args) => args
766 .position(|arg| arg.hir_id == child_id)
767 .zip(expr_sig(cx, func))
768 .and_then(|(i, sig)| {
769 sig.input_with_hir(i).map(|(hir_ty, ty)| match hir_ty {
770 // Type inference for closures can depend on how they're called. Only go by the explicit
772 Some(hir_ty) => binding_ty_auto_deref_stability(cx, hir_ty, precedence, ty.bound_vars()),
774 if let ty::Param(param_ty) = ty.skip_binder().kind() {
775 needless_borrow_impl_arg_position(cx, parent, i, *param_ty, e, precedence, msrv)
777 ty_auto_deref_stability(cx, cx.tcx.erase_late_bound_regions(ty), precedence)
783 ExprKind::MethodCall(_, args, _) => {
784 let id = cx.typeck_results().type_dependent_def_id(parent.hir_id).unwrap();
785 args.iter().position(|arg| arg.hir_id == child_id).map(|i| {
787 // Check for calls to trait methods where the trait is implemented on a reference.
788 // Two cases need to be handled:
789 // * `self` methods on `&T` will never have auto-borrow
790 // * `&self` methods on `&T` can have auto-borrow, but `&self` methods on `T` will take
792 if e.hir_id != child_id {
793 Position::ReborrowStable(precedence)
794 } else if let Some(trait_id) = cx.tcx.trait_of_item(id)
795 && let arg_ty = cx.tcx.erase_regions(cx.typeck_results().expr_ty_adjusted(e))
796 && let ty::Ref(_, sub_ty, _) = *arg_ty.kind()
797 && let subs = match cx
799 .node_substs_opt(parent.hir_id)
800 .and_then(|subs| subs.get(1..))
802 Some(subs) => cx.tcx.mk_substs(subs.iter().copied()),
803 None => cx.tcx.mk_substs(std::iter::empty::<ty::subst::GenericArg<'_>>()),
804 } && let impl_ty = if cx.tcx.fn_sig(id).skip_binder().inputs()[0].is_ref() {
805 // Trait methods taking `&self`
808 // Trait methods taking `self`
810 } && impl_ty.is_ref()
811 && cx.tcx.infer_ctxt().enter(|infcx|
813 .type_implements_trait(trait_id, impl_ty, subs, cx.param_env)
814 .must_apply_modulo_regions()
817 Position::MethodReceiverRefImpl
819 Position::MethodReceiver
822 let ty = cx.tcx.fn_sig(id).skip_binder().inputs()[i];
823 if let ty::Param(param_ty) = ty.kind() {
824 needless_borrow_impl_arg_position(cx, parent, i, *param_ty, e, precedence, msrv)
826 ty_auto_deref_stability(
828 cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).input(i)),
836 ExprKind::Struct(path, fields, _) => {
837 let variant = variant_of_res(cx, cx.qpath_res(path, parent.hir_id));
840 .find(|f| f.expr.hir_id == child_id)
842 .and_then(|(field, variant)| variant.fields.iter().find(|f| f.name == field.ident.name))
844 ty_auto_deref_stability(cx, cx.tcx.type_of(field.did), precedence).position_for_arg()
847 ExprKind::Field(child, name) if child.hir_id == e.hir_id => Some(Position::FieldAccess(name.name)),
848 ExprKind::Unary(UnOp::Deref, child) if child.hir_id == e.hir_id => Some(Position::Deref),
849 ExprKind::Match(child, _, MatchSource::TryDesugar | MatchSource::AwaitDesugar)
850 | ExprKind::Index(child, _)
851 if child.hir_id == e.hir_id =>
853 Some(Position::Postfix)
855 _ if child_id == e.hir_id => {
856 precedence = parent.precedence().order();
864 .unwrap_or(Position::Other(precedence));
865 (position, adjustments)
868 fn closure_result_position<'tcx>(
869 cx: &LateContext<'tcx>,
870 closure: &'tcx Closure<'_>,
874 match closure.fn_decl.output {
875 FnRetTy::Return(hir_ty) => {
876 if let Some(sig) = ty_sig(cx, ty)
877 && let Some(output) = sig.output()
879 binding_ty_auto_deref_stability(cx, hir_ty, precedence, output.bound_vars())
881 Position::Other(precedence)
884 FnRetTy::DefaultReturn(_) => Position::Other(precedence),
888 // Checks the stability of auto-deref when assigned to a binding with the given explicit type.
891 // let x = Box::new(Box::new(0u32));
892 // let y1: &Box<_> = x.deref();
893 // let y2: &Box<_> = &x;
895 // Here `y1` and `y2` would resolve to different types, so the type `&Box<_>` is not stable when
896 // switching to auto-dereferencing.
897 fn binding_ty_auto_deref_stability<'tcx>(
898 cx: &LateContext<'tcx>,
899 ty: &'tcx hir::Ty<'_>,
901 binder_args: &'tcx List<BoundVariableKind>,
903 let TyKind::Rptr(_, ty) = &ty.kind else {
904 return Position::Other(precedence);
909 break match ty.ty.kind {
910 TyKind::Rptr(_, ref ref_ty) => {
915 QPath::TypeRelative(_, path)
919 segments: [.., path], ..
923 if let Some(args) = path.args
924 && args.args.iter().any(|arg| match arg {
925 GenericArg::Infer(_) => true,
926 GenericArg::Type(ty) => ty_contains_infer(ty),
930 Position::ReborrowStable(precedence)
932 Position::DerefStable(
935 .erase_late_bound_regions(Binder::bind_with_vars(
936 cx.typeck_results().node_type(ty.ty.hir_id),
939 .is_sized(cx.tcx.at(DUMMY_SP), cx.param_env.without_caller_bounds()),
943 TyKind::Slice(_) => Position::DerefStable(precedence, false),
944 TyKind::Array(..) | TyKind::Ptr(_) | TyKind::BareFn(_) => Position::DerefStable(precedence, true),
947 | TyKind::Path(_) => Position::DerefStable(
950 .erase_late_bound_regions(Binder::bind_with_vars(
951 cx.typeck_results().node_type(ty.ty.hir_id),
954 .is_sized(cx.tcx.at(DUMMY_SP), cx.param_env.without_caller_bounds()),
956 TyKind::OpaqueDef(..) | TyKind::Infer | TyKind::Typeof(..) | TyKind::TraitObject(..) | TyKind::Err => {
957 Position::ReborrowStable(precedence)
963 // Checks whether a type is inferred at some point.
964 // e.g. `_`, `Box<_>`, `[_]`
965 fn ty_contains_infer(ty: &hir::Ty<'_>) -> bool {
967 impl Visitor<'_> for V {
968 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
972 TyKind::OpaqueDef(..) | TyKind::Infer | TyKind::Typeof(_) | TyKind::Err
981 fn visit_generic_arg(&mut self, arg: &GenericArg<'_>) {
982 if self.0 || matches!(arg, GenericArg::Infer(_)) {
984 } else if let GenericArg::Type(ty) = arg {
989 let mut v = V(false);
995 // * child is an expression of the form `&e` in an argument position requiring an `impl Trait`
996 // * `e`'s type implements `Trait` and is copyable
997 // If the conditions are met, returns `Some(Position::ImplArg(..))`; otherwise, returns `None`.
998 // The "is copyable" condition is to avoid the case where removing the `&` means `e` would have to
999 // be moved, but it cannot be.
1000 fn needless_borrow_impl_arg_position<'tcx>(
1001 cx: &LateContext<'tcx>,
1002 parent: &Expr<'tcx>,
1005 mut expr: &Expr<'tcx>,
1007 msrv: Option<RustcVersion>,
1009 let destruct_trait_def_id = cx.tcx.lang_items().destruct_trait();
1010 let sized_trait_def_id = cx.tcx.lang_items().sized_trait();
1012 let Some(callee_def_id) = fn_def_id(cx, parent) else { return Position::Other(precedence) };
1013 let fn_sig = cx.tcx.fn_sig(callee_def_id).skip_binder();
1014 let substs_with_expr_ty = cx
1016 .node_substs(if let ExprKind::Call(callee, _) = parent.kind {
1022 let predicates = cx.tcx.param_env(callee_def_id).caller_bounds();
1023 let projection_predicates = predicates
1025 .filter_map(|predicate| {
1026 if let PredicateKind::Projection(projection_predicate) = predicate.kind().skip_binder() {
1027 Some(projection_predicate)
1032 .collect::<Vec<_>>();
1034 let mut trait_with_ref_mut_self_method = false;
1036 // If no traits were found, or only the `Destruct`, `Sized`, or `Any` traits were found, return.
1039 .filter_map(|predicate| {
1040 if let PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder()
1041 && trait_predicate.trait_ref.self_ty() == param_ty.to_ty(cx.tcx)
1043 Some(trait_predicate.trait_ref.def_id)
1048 .inspect(|trait_def_id| {
1049 trait_with_ref_mut_self_method |= has_ref_mut_self_method(cx, *trait_def_id);
1051 .all(|trait_def_id| {
1052 Some(trait_def_id) == destruct_trait_def_id
1053 || Some(trait_def_id) == sized_trait_def_id
1054 || cx.tcx.is_diagnostic_item(sym::Any, trait_def_id)
1057 return Position::Other(precedence);
1060 // `substs_with_referent_ty` can be constructed outside of `check_referent` because the same
1061 // elements are modified each time `check_referent` is called.
1062 let mut substs_with_referent_ty = substs_with_expr_ty.to_vec();
1064 let mut check_referent = |referent| {
1065 let referent_ty = cx.typeck_results().expr_ty(referent);
1067 if !is_copy(cx, referent_ty) {
1071 // https://github.com/rust-lang/rust-clippy/pull/9136#pullrequestreview-1037379321
1072 if trait_with_ref_mut_self_method && !matches!(referent_ty.kind(), ty::Ref(_, _, Mutability::Mut)) {
1082 &projection_predicates,
1083 &mut substs_with_referent_ty,
1088 predicates.iter().all(|predicate| {
1089 if let PredicateKind::Trait(trait_predicate) = predicate.kind().skip_binder()
1090 && cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_predicate.trait_ref.def_id)
1091 && let ty::Param(param_ty) = trait_predicate.self_ty().kind()
1092 && let GenericArgKind::Type(ty) = substs_with_referent_ty[param_ty.index as usize].unpack()
1094 && !meets_msrv(msrv, msrvs::ARRAY_INTO_ITERATOR)
1099 let predicate = EarlyBinder(predicate).subst(cx.tcx, &substs_with_referent_ty);
1100 let obligation = Obligation::new(ObligationCause::dummy(), cx.param_env, predicate);
1103 .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
1107 let mut needless_borrow = false;
1108 while let ExprKind::AddrOf(_, _, referent) = expr.kind {
1109 if !check_referent(referent) {
1113 needless_borrow = true;
1116 if needless_borrow {
1117 Position::ImplArg(expr.hir_id)
1119 Position::Other(precedence)
1123 fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool {
1125 .associated_items(trait_def_id)
1126 .in_definition_order()
1128 if assoc_item.fn_has_self_parameter {
1129 let self_ty = cx.tcx.fn_sig(assoc_item.def_id).skip_binder().inputs()[0];
1130 matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Mut))
1137 // Iteratively replaces `param_ty` with `new_ty` in `substs`, and similarly for each resulting
1138 // projected type that is a type parameter. Returns `false` if replacing the types would have an
1139 // effect on the function signature beyond substituting `new_ty` for `param_ty`.
1140 // See: https://github.com/rust-lang/rust-clippy/pull/9136#discussion_r927212757
1141 fn replace_types<'tcx>(
1142 cx: &LateContext<'tcx>,
1145 fn_sig: FnSig<'tcx>,
1147 projection_predicates: &[ProjectionPredicate<'tcx>],
1148 substs: &mut [ty::GenericArg<'tcx>],
1150 let mut replaced = BitSet::new_empty(substs.len());
1152 let mut deque = VecDeque::with_capacity(substs.len());
1153 deque.push_back((param_ty, new_ty));
1155 while let Some((param_ty, new_ty)) = deque.pop_front() {
1156 // If `replaced.is_empty()`, then `param_ty` and `new_ty` are those initially passed in.
1161 .all(|(i, ty)| (replaced.is_empty() && i == arg_index) || !contains_ty(ty, param_ty.to_ty(cx.tcx)))
1166 substs[param_ty.index as usize] = ty::GenericArg::from(new_ty);
1168 // The `replaced.insert(...)` check provides some protection against infinite loops.
1169 if replaced.insert(param_ty.index) {
1170 for projection_predicate in projection_predicates {
1171 if projection_predicate.projection_ty.self_ty() == param_ty.to_ty(cx.tcx)
1172 && let ty::Term::Ty(term_ty) = projection_predicate.term
1173 && let ty::Param(term_param_ty) = term_ty.kind()
1175 let item_def_id = projection_predicate.projection_ty.item_def_id;
1176 let assoc_item = cx.tcx.associated_item(item_def_id);
1177 let projection = cx.tcx
1178 .mk_projection(assoc_item.def_id, cx.tcx.mk_substs_trait(new_ty, &[]));
1180 if let Ok(projected_ty) = cx.tcx.try_normalize_erasing_regions(cx.param_env, projection)
1181 && substs[term_param_ty.index as usize] != ty::GenericArg::from(projected_ty)
1183 deque.push_back((*term_param_ty, projected_ty));
1193 struct TyPosition<'tcx> {
1195 ty: Option<Ty<'tcx>>,
1197 impl From<Position> for TyPosition<'_> {
1198 fn from(position: Position) -> Self {
1199 Self { position, ty: None }
1202 impl<'tcx> TyPosition<'tcx> {
1203 fn new_deref_stable_for_result(precedence: i8, ty: Ty<'tcx>) -> Self {
1205 position: Position::ReborrowStable(precedence),
1209 fn position_for_result(self, cx: &LateContext<'tcx>) -> Position {
1210 match (self.position, self.ty) {
1211 (Position::ReborrowStable(precedence), Some(ty)) => {
1212 Position::DerefStable(precedence, ty.is_sized(cx.tcx.at(DUMMY_SP), cx.param_env))
1214 (position, _) => position,
1217 fn position_for_arg(self) -> Position {
1222 // Checks whether a type is stable when switching to auto dereferencing,
1223 fn ty_auto_deref_stability<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, precedence: i8) -> TyPosition<'tcx> {
1224 let ty::Ref(_, mut ty, _) = *ty.kind() else {
1225 return Position::Other(precedence).into();
1229 break match *ty.kind() {
1230 ty::Ref(_, ref_ty, _) => {
1234 ty::Param(_) => TyPosition::new_deref_stable_for_result(precedence, ty),
1235 ty::Infer(_) | ty::Error(_) | ty::Bound(..) | ty::Opaque(..) | ty::Placeholder(_) | ty::Dynamic(..) => {
1236 Position::ReborrowStable(precedence).into()
1238 ty::Adt(..) if ty.has_placeholders() || ty.has_opaque_types() => {
1239 Position::ReborrowStable(precedence).into()
1241 ty::Adt(_, substs) if substs.has_param_types_or_consts() => {
1242 TyPosition::new_deref_stable_for_result(precedence, ty)
1251 | ty::FnPtr(_) => Position::DerefStable(precedence, true).into(),
1252 ty::Str | ty::Slice(..) => Position::DerefStable(precedence, false).into(),
1257 | ty::GeneratorWitness(..)
1261 | ty::Projection(_) => Position::DerefStable(
1263 ty.is_sized(cx.tcx.at(DUMMY_SP), cx.param_env.without_caller_bounds()),
1270 fn ty_contains_field(ty: Ty<'_>, name: Symbol) -> bool {
1271 if let ty::Adt(adt, _) = *ty.kind() {
1272 adt.is_struct() && adt.all_fields().any(|f| f.name == name)
1278 #[expect(clippy::needless_pass_by_value, clippy::too_many_lines)]
1279 fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data: StateData) {
1281 State::DerefMethod {
1286 let mut app = Applicability::MachineApplicable;
1287 let (expr_str, expr_is_macro_call) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
1288 let ty = cx.typeck_results().expr_ty(expr);
1289 let (_, ref_count) = peel_mid_ty_refs(ty);
1290 let deref_str = if ty_changed_count >= ref_count && ref_count != 0 {
1291 // a deref call changing &T -> &U requires two deref operators the first time
1292 // this occurs. One to remove the reference, a second to call the deref impl.
1293 "*".repeat(ty_changed_count + 1)
1295 "*".repeat(ty_changed_count)
1297 let addr_of_str = if ty_changed_count < ref_count {
1298 // Check if a reborrow from &mut T -> &T is required.
1299 if target_mut == Mutability::Not && matches!(ty.kind(), ty::Ref(_, _, Mutability::Mut)) {
1304 } else if target_mut == Mutability::Mut {
1310 let expr_str = if !expr_is_macro_call && is_final_ufcs && expr.precedence().order() < PREC_PREFIX {
1311 format!("({})", expr_str)
1313 expr_str.into_owned()
1318 EXPLICIT_DEREF_METHODS,
1321 Mutability::Not => "explicit `deref` method call",
1322 Mutability::Mut => "explicit `deref_mut` method call",
1325 format!("{}{}{}", addr_of_str, deref_str, expr_str),
1329 State::DerefedBorrow(state) => {
1330 let mut app = Applicability::MachineApplicable;
1331 let snip_expr = state.snip_expr.map_or(expr, |hir_id| cx.tcx.hir().expect_expr(hir_id));
1332 let (snip, snip_is_macro) = snippet_with_context(cx, snip_expr.span, data.span.ctxt(), "..", &mut app);
1333 span_lint_hir_and_then(cx, NEEDLESS_BORROW, data.hir_id, data.span, state.msg, |diag| {
1334 let calls_field = matches!(expr.kind, ExprKind::Field(..)) && matches!(data.position, Position::Callee);
1335 let sugg = if !snip_is_macro
1336 && !has_enclosing_paren(&snip)
1337 && (expr.precedence().order() < data.position.precedence() || calls_field)
1339 format!("({})", snip)
1343 diag.span_suggestion(data.span, "change this to", sugg, app);
1346 State::ExplicitDeref { mutability } => {
1350 | ExprKind::ConstBlock(_)
1352 | ExprKind::Loop(..)
1353 | ExprKind::Match(..)
1354 ) && matches!(data.position, Position::DerefStable(_, true))
1356 // Rustc bug: auto deref doesn't work on block expression when targeting sized types.
1360 let (prefix, precedence) = if let Some(mutability) = mutability
1361 && !cx.typeck_results().expr_ty(expr).is_ref()
1363 let prefix = match mutability {
1364 Mutability::Not => "&",
1365 Mutability::Mut => "&mut ",
1369 ("", data.position.precedence())
1371 span_lint_hir_and_then(
1373 EXPLICIT_AUTO_DEREF,
1376 "deref which would be done by auto-deref",
1378 let mut app = Applicability::MachineApplicable;
1379 let (snip, snip_is_macro) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
1381 if !snip_is_macro && expr.precedence().order() < precedence && !has_enclosing_paren(&snip) {
1382 format!("{}({})", prefix, snip)
1384 format!("{}{}", prefix, snip)
1386 diag.span_suggestion(data.span, "try this", sugg, app);
1390 State::ExplicitDerefField { .. } => {
1394 | ExprKind::ConstBlock(_)
1396 | ExprKind::Loop(..)
1397 | ExprKind::Match(..)
1398 ) && matches!(data.position, Position::DerefStable(_, true))
1400 // Rustc bug: auto deref doesn't work on block expression when targeting sized types.
1404 span_lint_hir_and_then(
1406 EXPLICIT_AUTO_DEREF,
1409 "deref which would be done by auto-deref",
1411 let mut app = Applicability::MachineApplicable;
1412 let snip = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app).0;
1413 diag.span_suggestion(data.span, "try this", snip.into_owned(), app);
1417 State::Borrow { .. } | State::Reborrow { .. } => (),
1421 impl Dereferencing {
1422 fn check_local_usage<'tcx>(&mut self, cx: &LateContext<'tcx>, e: &Expr<'tcx>, local: HirId) {
1423 if let Some(outer_pat) = self.ref_locals.get_mut(&local) {
1424 if let Some(pat) = outer_pat {
1425 // Check for auto-deref
1427 cx.typeck_results().expr_adjustments(e),
1430 kind: Adjust::Deref(_),
1434 kind: Adjust::Deref(_),
1440 match get_parent_expr(cx, e) {
1441 // Field accesses are the same no matter the number of references.
1443 kind: ExprKind::Field(..),
1448 kind: ExprKind::Unary(UnOp::Deref, _),
1450 }) if !span.from_expansion() => {
1451 // Remove explicit deref.
1452 let snip = snippet_with_context(cx, e.span, span.ctxt(), "..", &mut pat.app).0;
1453 pat.replacements.push((span, snip.into()));
1455 Some(parent) if !parent.span.from_expansion() => {
1456 // Double reference might be needed at this point.
1457 if parent.precedence().order() == PREC_POSTFIX {
1458 // Parentheses would be needed here, don't lint.
1461 pat.always_deref = false;
1462 let snip = snippet_with_context(cx, e.span, parent.span.ctxt(), "..", &mut pat.app).0;
1463 pat.replacements.push((e.span, format!("&{}", snip)));
1466 _ if !e.span.from_expansion() => {
1467 // Double reference might be needed at this point.
1468 pat.always_deref = false;
1469 let snip = snippet_with_applicability(cx, e.span, "..", &mut pat.app);
1470 pat.replacements.push((e.span, format!("&{}", snip)));
1472 // Edge case for macros. The span of the identifier will usually match the context of the
1473 // binding, but not if the identifier was created in a macro. e.g. `concat_idents` and proc
1475 _ => *outer_pat = None,