1 use crate::reference::DEREF_ADDROF;
2 use clippy_utils::diagnostics::span_lint_and_then;
3 use clippy_utils::source::snippet_opt;
4 use clippy_utils::ty::implements_trait;
5 use clippy_utils::{get_parent_expr, is_lint_allowed};
6 use rustc_errors::Applicability;
7 use rustc_hir::{ExprKind, UnOp};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::mir::Mutability;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 declare_clippy_lint! {
15 /// Checks for `&*(&T)`.
17 /// ### Why is this bad?
18 /// Dereferencing and then borrowing a reference value has no effect in most cases.
20 /// ### Known problems
21 /// False negative on such code:
24 /// let addr_x = &x as *const _ as usize;
25 /// let addr_y = &&*x as *const _ as usize; // assert ok now, and lint triggered.
26 /// // But if we fix it, assert will fail.
27 /// assert_ne!(addr_x, addr_y);
32 /// let s = &String::new();
34 /// let a: &String = &* s;
39 /// # let s = &String::new();
40 /// let a: &String = s;
42 #[clippy::version = "1.63.0"]
45 "deref on an immutable reference returns the same type as itself"
48 declare_lint_pass!(BorrowDerefRef => [BORROW_DEREF_REF]);
50 impl LateLintPass<'_> for BorrowDerefRef {
51 fn check_expr(&mut self, cx: &LateContext<'_>, e: &rustc_hir::Expr<'_>) {
53 if !e.span.from_expansion();
54 if let ExprKind::AddrOf(_, Mutability::Not, addrof_target) = e.kind;
55 if !addrof_target.span.from_expansion();
56 if let ExprKind::Unary(UnOp::Deref, deref_target) = addrof_target.kind;
57 if !deref_target.span.from_expansion();
58 if !matches!(deref_target.kind, ExprKind::Unary(UnOp::Deref, ..) );
59 let ref_ty = cx.typeck_results().expr_ty(deref_target);
60 if let ty::Ref(_, inner_ty, Mutability::Not) = ref_ty.kind();
63 if let Some(parent_expr) = get_parent_expr(cx, e){
64 if matches!(parent_expr.kind, ExprKind::Unary(UnOp::Deref, ..)) &&
65 !is_lint_allowed(cx, DEREF_ADDROF, parent_expr.hir_id) {
69 // modification to `&mut &*x` is different from `&mut x`
70 if matches!(deref_target.kind, ExprKind::Path(..)
73 | ExprKind::Unary(UnOp::Deref, ..))
74 && matches!(parent_expr.kind, ExprKind::AddrOf(_, Mutability::Mut, _)) {
83 "deref on an immutable reference",
87 "if you would like to reborrow, try removing `&*`",
88 snippet_opt(cx, deref_target.span).unwrap(),
89 Applicability::MachineApplicable
92 // has deref trait -> give 2 help
93 // doesn't have deref trait -> give 1 help
94 if let Some(deref_trait_id) = cx.tcx.lang_items().deref_trait(){
95 if !implements_trait(cx, *inner_ty, deref_trait_id, &[]) {
100 diag.span_suggestion(
102 "if you would like to deref, try using `&**`",
105 &snippet_opt(cx, deref_target.span).unwrap(),
107 Applicability::MaybeIncorrect