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 triggerd.
26 /// // But if we fix it, assert will fail.
27 /// assert_ne!(addr_x, addr_y);
32 /// let s = &String::new();
35 /// let a: &String = &* s;
39 /// let a: &String = s;
42 /// fn foo(_: &str){ }
44 #[clippy::version = "1.59.0"]
47 "deref on an immutable reference returns the same type as itself"
50 declare_lint_pass!(BorrowDerefRef => [BORROW_DEREF_REF]);
52 impl LateLintPass<'_> for BorrowDerefRef {
53 fn check_expr(&mut self, cx: &LateContext<'_>, e: &rustc_hir::Expr<'_>) {
55 if !e.span.from_expansion();
56 if let ExprKind::AddrOf(_, Mutability::Not, addrof_target) = e.kind;
57 if !addrof_target.span.from_expansion();
58 if let ExprKind::Unary(UnOp::Deref, deref_target) = addrof_target.kind;
59 if !deref_target.span.from_expansion();
60 if !matches!(deref_target.kind, ExprKind::Unary(UnOp::Deref, ..) );
61 let ref_ty = cx.typeck_results().expr_ty(deref_target);
62 if let ty::Ref(_, inner_ty, Mutability::Not) = ref_ty.kind();
65 if let Some(parent_expr) = get_parent_expr(cx, e){
66 if matches!(parent_expr.kind, ExprKind::Unary(UnOp::Deref, ..)) &&
67 !is_lint_allowed(cx, DEREF_ADDROF, parent_expr.hir_id) {
71 // modification to `&mut &*x` is different from `&mut x`
72 if matches!(deref_target.kind, ExprKind::Path(..)
75 | ExprKind::Unary(UnOp::Deref, ..))
76 && matches!(parent_expr.kind, ExprKind::AddrOf(_, Mutability::Mut, _)) {
85 "deref on an immutable reference",
89 "if you would like to reborrow, try removing `&*`",
90 snippet_opt(cx, deref_target.span).unwrap(),
91 Applicability::MachineApplicable
94 // has deref trait -> give 2 help
95 // doesn't have deref trait -> give 1 help
96 if let Some(deref_trait_id) = cx.tcx.lang_items().deref_trait(){
97 if !implements_trait(cx, *inner_ty, deref_trait_id, &[]) {
102 diag.span_suggestion(
104 "if you would like to deref, try using `&**`",
107 &snippet_opt(cx, deref_target.span).unwrap(),
109 Applicability::MaybeIncorrect