1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_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::peel_mid_ty_refs;
5 use clippy_utils::{get_parent_expr, get_parent_node, is_lint_allowed, path_to_local};
6 use rustc_ast::util::parser::{PREC_POSTFIX, PREC_PREFIX};
7 use rustc_data_structures::fx::FxIndexMap;
8 use rustc_errors::Applicability;
10 BindingAnnotation, Body, BodyId, BorrowKind, Destination, Expr, ExprKind, HirId, MatchSource, Mutability, Node,
13 use rustc_lint::{LateContext, LateLintPass};
14 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability};
15 use rustc_middle::ty::{self, Ty, TyCtxt, TypeckResults};
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::{symbol::sym, Span};
19 declare_clippy_lint! {
21 /// Checks for explicit `deref()` or `deref_mut()` method calls.
23 /// ### Why is this bad?
24 /// Dereferencing by `&*x` or `&mut *x` is clearer and more concise,
25 /// when not part of a method chain.
29 /// use std::ops::Deref;
30 /// let a: &mut String = &mut String::from("foo");
31 /// let b: &str = a.deref();
33 /// Could be written as:
35 /// let a: &mut String = &mut String::from("foo");
39 /// This lint excludes
41 /// let _ = d.unwrap().deref();
43 #[clippy::version = "1.44.0"]
44 pub EXPLICIT_DEREF_METHODS,
46 "Explicit use of deref or deref_mut method while not in a method chain."
49 declare_clippy_lint! {
51 /// Checks for address of operations (`&`) that are going to
52 /// be dereferenced immediately by the compiler.
54 /// ### Why is this bad?
55 /// Suggests that the receiver of the expression borrows
60 /// fn fun(_a: &i32) {}
63 /// let x: &i32 = &&&&&&5;
70 #[clippy::version = "pre 1.29.0"]
73 "taking a reference that is going to be automatically dereferenced"
76 declare_clippy_lint! {
78 /// Checks for `ref` bindings which create a reference to a reference.
80 /// ### Why is this bad?
81 /// The address-of operator at the use site is clearer about the need for a reference.
87 /// if let Some(ref x) = x {
93 /// if let Some(x) = x {
97 #[clippy::version = "1.54.0"]
98 pub REF_BINDING_TO_REFERENCE,
100 "`ref` binding to a reference"
103 impl_lint_pass!(Dereferencing => [
104 EXPLICIT_DEREF_METHODS,
106 REF_BINDING_TO_REFERENCE,
110 pub struct Dereferencing {
111 state: Option<(State, StateData)>,
113 // While parsing a `deref` method call in ufcs form, the path to the function is itself an
114 // expression. This is to store the id of that expression so it can be skipped when
115 // `check_expr` is called for it.
116 skip_expr: Option<HirId>,
118 /// The body the first local was found in. Used to emit lints when the traversal of the body has
119 /// been finished. Note we can't lint at the end of every body as they can be nested within each
121 current_body: Option<BodyId>,
122 /// The list of locals currently being checked by the lint.
123 /// If the value is `None`, then the binding has been seen as a ref pattern, but is not linted.
124 /// This is needed for or patterns where one of the branches can be linted, but another can not
127 /// e.g. `m!(x) | Foo::Bar(ref x)`
128 ref_locals: FxIndexMap<HirId, Option<RefPat>>,
132 /// Span of the top level expression
137 // Any number of deref method calls.
139 // The number of calls in a sequence which changed the referenced type
140 ty_changed_count: usize,
142 /// The required mutability
143 target_mut: Mutability,
147 required_precedence: i8,
152 // A reference operation considered by this lint pass
160 /// Whether every usage of the binding is dereferenced.
162 /// The spans of all the ref bindings for this local.
164 /// The applicability of this suggestion.
166 /// All the replacements which need to be made.
167 replacements: Vec<(Span, String)>,
170 impl<'tcx> LateLintPass<'tcx> for Dereferencing {
171 #[expect(clippy::too_many_lines)]
172 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
173 // Skip path expressions from deref calls. e.g. `Deref::deref(e)`
174 if Some(expr.hir_id) == self.skip_expr.take() {
178 if let Some(local) = path_to_local(expr) {
179 self.check_local_usage(cx, expr, local);
182 // Stop processing sub expressions when a macro call is seen
183 if expr.span.from_expansion() {
184 if let Some((state, data)) = self.state.take() {
185 report(cx, expr, state, data);
190 let typeck = cx.typeck_results();
191 let (kind, sub_expr) = if let Some(x) = try_parse_ref_op(cx.tcx, typeck, expr) {
194 // The whole chain of reference operations has been seen
195 if let Some((state, data)) = self.state.take() {
196 report(cx, expr, state, data);
201 match (self.state.take(), kind) {
203 let parent = get_parent_node(cx.tcx, expr.hir_id);
204 let expr_ty = typeck.expr_ty(expr);
207 RefOp::Method(target_mut)
208 if !is_lint_allowed(cx, EXPLICIT_DEREF_METHODS, expr.hir_id)
209 && is_linted_explicit_deref_position(parent, expr.hir_id, expr.span) =>
213 ty_changed_count: if deref_method_same_type(expr_ty, typeck.expr_ty(sub_expr)) {
218 is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
221 StateData { span: expr.span },
225 // Find the number of times the borrow is auto-derefed.
226 let mut iter = find_adjustments(cx.tcx, typeck, expr).iter();
227 let mut deref_count = 0usize;
228 let next_adjust = loop {
231 if !matches!(adjust.kind, Adjust::Deref(_)) {
233 } else if !adjust.target.is_ref() {
243 // Determine the required number of references before any can be removed. In all cases the
244 // reference made by the current expression will be removed. After that there are four cases to
247 // 1. Auto-borrow will trigger in the current position, so no further references are required.
248 // 2. Auto-deref ends at a reference, or the underlying type, so one extra needs to be left to
249 // handle the automatically inserted re-borrow.
250 // 3. Auto-deref hits a user-defined `Deref` impl, so at least one reference needs to exist to
252 // 4. If the chain of non-user-defined derefs ends with a mutable re-borrow, and re-borrow
253 // adjustments will not be inserted automatically, then leave one further reference to avoid
254 // moving a mutable borrow.
256 // fn foo<T>(x: &mut Option<&mut T>, y: &mut T) {
258 // // Removing the borrow will cause `x` to be moved
259 // Some(x) => &mut *x,
264 "this expression creates a reference which is immediately dereferenced by the compiler";
265 let borrow_msg = "this expression borrows a value the compiler would automatically borrow";
267 let (required_refs, required_precedence, msg) = if is_auto_borrow_position(parent, expr.hir_id)
269 (1, PREC_POSTFIX, if deref_count == 1 { borrow_msg } else { deref_msg })
270 } else if let Some(&Adjust::Borrow(AutoBorrow::Ref(_, mutability))) =
271 next_adjust.map(|a| &a.kind)
273 if matches!(mutability, AutoBorrowMutability::Mut { .. })
274 && !is_auto_reborrow_position(parent)
284 if deref_count >= required_refs {
286 State::DerefedBorrow {
287 // One of the required refs is for the current borrow expression, the remaining ones
288 // can't be removed without breaking the code. See earlier comment.
289 count: deref_count - required_refs,
293 StateData { span: expr.span },
313 ty_changed_count: if deref_method_same_type(typeck.expr_ty(expr), typeck.expr_ty(sub_expr)) {
318 is_final_ufcs: matches!(expr.kind, ExprKind::Call(..)),
326 State::DerefedBorrow {
336 State::DerefedBorrow {
345 (Some((state, data)), _) => report(cx, expr, state, data),
349 fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) {
350 if let PatKind::Binding(BindingAnnotation::Ref, id, name, _) = pat.kind {
351 if let Some(opt_prev_pat) = self.ref_locals.get_mut(&id) {
352 // This binding id has been seen before. Add this pattern to the list of changes.
353 if let Some(prev_pat) = opt_prev_pat {
354 if pat.span.from_expansion() {
355 // Doesn't match the context of the previous pattern. Can't lint here.
356 *opt_prev_pat = None;
358 prev_pat.spans.push(pat.span);
359 prev_pat.replacements.push((
361 snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut prev_pat.app)
371 if !pat.span.from_expansion();
372 if let ty::Ref(_, tam, _) = *cx.typeck_results().pat_ty(pat).kind();
373 // only lint immutable refs, because borrowed `&mut T` cannot be moved out
374 if let ty::Ref(_, _, Mutability::Not) = *tam.kind();
376 let mut app = Applicability::MachineApplicable;
377 let snip = snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut app).0;
378 self.current_body = self.current_body.or(cx.enclosing_body);
379 self.ref_locals.insert(
383 spans: vec![pat.span],
385 replacements: vec![(pat.span, snip.into())],
393 fn check_body_post(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
394 if Some(body.id()) == self.current_body {
395 for pat in self.ref_locals.drain(..).filter_map(|(_, x)| x) {
396 let replacements = pat.replacements;
400 if pat.always_deref {
403 REF_BINDING_TO_REFERENCE
406 "this pattern creates a reference to a reference",
408 diag.multipart_suggestion("try this", replacements, app);
412 self.current_body = None;
417 fn try_parse_ref_op<'tcx>(
419 typeck: &'tcx TypeckResults<'_>,
420 expr: &'tcx Expr<'_>,
421 ) -> Option<(RefOp, &'tcx Expr<'tcx>)> {
422 let (def_id, arg) = match expr.kind {
423 ExprKind::MethodCall(_, [arg], _) => (typeck.type_dependent_def_id(expr.hir_id)?, arg),
426 kind: ExprKind::Path(path),
431 ) => (typeck.qpath_res(path, *hir_id).opt_def_id()?, arg),
432 ExprKind::Unary(UnOp::Deref, sub_expr) if !typeck.expr_ty(sub_expr).is_unsafe_ptr() => {
433 return Some((RefOp::Deref, sub_expr));
435 ExprKind::AddrOf(BorrowKind::Ref, _, sub_expr) => return Some((RefOp::AddrOf, sub_expr)),
438 if tcx.is_diagnostic_item(sym::deref_method, def_id) {
439 Some((RefOp::Method(Mutability::Not), arg))
440 } else if tcx.trait_of_item(def_id)? == tcx.lang_items().deref_mut_trait()? {
441 Some((RefOp::Method(Mutability::Mut), arg))
447 // Checks whether the type for a deref call actually changed the type, not just the mutability of
449 fn deref_method_same_type(result_ty: Ty<'_>, arg_ty: Ty<'_>) -> bool {
450 match (result_ty.kind(), arg_ty.kind()) {
451 (ty::Ref(_, result_ty, _), ty::Ref(_, arg_ty, _)) => result_ty == arg_ty,
453 // The result type for a deref method is always a reference
454 // Not matching the previous pattern means the argument type is not a reference
455 // This means that the type did change
460 // Checks whether the parent node is a suitable context for switching from a deref method to the
462 fn is_linted_explicit_deref_position(parent: Option<Node<'_>>, child_id: HirId, child_span: Span) -> bool {
463 let parent = match parent {
464 Some(Node::Expr(e)) if e.span.ctxt() == child_span.ctxt() => e,
468 // Leave deref calls in the middle of a method chain.
469 // e.g. x.deref().foo()
470 ExprKind::MethodCall(_, [self_arg, ..], _) if self_arg.hir_id == child_id => false,
472 // Leave deref calls resulting in a called function
473 // e.g. (x.deref())()
474 ExprKind::Call(func_expr, _) if func_expr.hir_id == child_id => false,
476 // Makes an ugly suggestion
477 // e.g. *x.deref() => *&*x
478 ExprKind::Unary(UnOp::Deref, _)
479 // Postfix expressions would require parens
480 | ExprKind::Match(_, _, MatchSource::TryDesugar | MatchSource::AwaitDesugar)
481 | ExprKind::Field(..)
482 | ExprKind::Index(..)
483 | ExprKind::Err => false,
486 | ExprKind::ConstBlock(..)
489 | ExprKind::MethodCall(..)
491 | ExprKind::Binary(..)
492 | ExprKind::Unary(..)
496 | ExprKind::DropTemps(..)
499 | ExprKind::Match(..)
501 | ExprKind::Closure(..)
502 | ExprKind::Block(..)
503 | ExprKind::Assign(..)
504 | ExprKind::AssignOp(..)
506 | ExprKind::AddrOf(..)
507 | ExprKind::Break(..)
508 | ExprKind::Continue(..)
510 | ExprKind::InlineAsm(..)
511 | ExprKind::Struct(..)
512 | ExprKind::Repeat(..)
513 | ExprKind::Yield(..) => true,
517 /// Checks if the given expression is in a position which can be auto-reborrowed.
518 /// Note: This is only correct assuming auto-deref is already occurring.
519 fn is_auto_reborrow_position(parent: Option<Node<'_>>) -> bool {
521 Some(Node::Expr(parent)) => matches!(parent.kind, ExprKind::MethodCall(..) | ExprKind::Call(..)),
522 Some(Node::Local(_)) => true,
527 /// Checks if the given expression is a position which can auto-borrow.
528 fn is_auto_borrow_position(parent: Option<Node<'_>>, child_id: HirId) -> bool {
529 if let Some(Node::Expr(parent)) = parent {
531 // ExprKind::MethodCall(_, [self_arg, ..], _) => self_arg.hir_id == child_id,
532 ExprKind::Field(..) => true,
533 ExprKind::Call(f, _) => f.hir_id == child_id,
541 /// Adjustments are sometimes made in the parent block rather than the expression itself.
542 fn find_adjustments<'tcx>(
544 typeck: &'tcx TypeckResults<'_>,
545 expr: &'tcx Expr<'_>,
546 ) -> &'tcx [Adjustment<'tcx>] {
548 let mut iter = map.parent_iter(expr.hir_id);
552 match typeck.expr_adjustments(prev) {
557 match iter.next().map(|(_, x)| x) {
558 Some(Node::Block(_)) => {
559 if let Some((_, Node::Expr(e))) = iter.next() {
562 // This shouldn't happen. Blocks are always contained in an expression.
566 Some(Node::Expr(&Expr {
567 kind: ExprKind::Break(Destination { target_id: Ok(id), .. }, _),
570 if let Some(Node::Expr(e)) = map.find(id) {
572 iter = map.parent_iter(id);
574 // This shouldn't happen. The destination should exist.
583 #[expect(clippy::needless_pass_by_value)]
584 fn report(cx: &LateContext<'_>, expr: &Expr<'_>, state: State, data: StateData) {
591 let mut app = Applicability::MachineApplicable;
592 let (expr_str, expr_is_macro_call) = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app);
593 let ty = cx.typeck_results().expr_ty(expr);
594 let (_, ref_count) = peel_mid_ty_refs(ty);
595 let deref_str = if ty_changed_count >= ref_count && ref_count != 0 {
596 // a deref call changing &T -> &U requires two deref operators the first time
597 // this occurs. One to remove the reference, a second to call the deref impl.
598 "*".repeat(ty_changed_count + 1)
600 "*".repeat(ty_changed_count)
602 let addr_of_str = if ty_changed_count < ref_count {
603 // Check if a reborrow from &mut T -> &T is required.
604 if target_mut == Mutability::Not && matches!(ty.kind(), ty::Ref(_, _, Mutability::Mut)) {
609 } else if target_mut == Mutability::Mut {
615 let expr_str = if !expr_is_macro_call && is_final_ufcs && expr.precedence().order() < PREC_PREFIX {
616 format!("({})", expr_str)
618 expr_str.into_owned()
623 EXPLICIT_DEREF_METHODS,
626 Mutability::Not => "explicit `deref` method call",
627 Mutability::Mut => "explicit `deref_mut` method call",
630 format!("{}{}{}", addr_of_str, deref_str, expr_str),
634 State::DerefedBorrow {
639 let mut app = Applicability::MachineApplicable;
640 let snip = snippet_with_context(cx, expr.span, data.span.ctxt(), "..", &mut app).0;
647 if required_precedence > expr.precedence().order() && !has_enclosing_paren(&snip) {
648 format!("({})", snip)
659 fn check_local_usage(&mut self, cx: &LateContext<'_>, e: &Expr<'_>, local: HirId) {
660 if let Some(outer_pat) = self.ref_locals.get_mut(&local) {
661 if let Some(pat) = outer_pat {
662 // Check for auto-deref
664 cx.typeck_results().expr_adjustments(e),
667 kind: Adjust::Deref(_),
671 kind: Adjust::Deref(_),
677 match get_parent_expr(cx, e) {
678 // Field accesses are the same no matter the number of references.
680 kind: ExprKind::Field(..),
685 kind: ExprKind::Unary(UnOp::Deref, _),
687 }) if !span.from_expansion() => {
688 // Remove explicit deref.
689 let snip = snippet_with_context(cx, e.span, span.ctxt(), "..", &mut pat.app).0;
690 pat.replacements.push((span, snip.into()));
692 Some(parent) if !parent.span.from_expansion() => {
693 // Double reference might be needed at this point.
694 if parent.precedence().order() == PREC_POSTFIX {
695 // Parentheses would be needed here, don't lint.
698 pat.always_deref = false;
699 let snip = snippet_with_context(cx, e.span, parent.span.ctxt(), "..", &mut pat.app).0;
700 pat.replacements.push((e.span, format!("&{}", snip)));
703 _ if !e.span.from_expansion() => {
704 // Double reference might be needed at this point.
705 pat.always_deref = false;
706 let snip = snippet_with_applicability(cx, e.span, "..", &mut pat.app);
707 pat.replacements.push((e.span, format!("&{}", snip)));
709 // Edge case for macros. The span of the identifier will usually match the context of the
710 // binding, but not if the identifier was created in a macro. e.g. `concat_idents` and proc
712 _ => *outer_pat = None,