]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs
Rollup merge of #101256 - andrewpollack:fuchsia-docs-adding, r=tmandry
[rust.git] / src / tools / clippy / clippy_lints / src / borrow_deref_ref.rs
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;
10 use rustc_middle::ty;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for `&*(&T)`.
16     ///
17     /// ### Why is this bad?
18     /// Dereferencing and then borrowing a reference value has no effect in most cases.
19     ///
20     /// ### Known problems
21     /// False negative on such code:
22     /// ```
23     /// let x = &12;
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);
28     /// ```
29     ///
30     /// ### Example
31     /// ```rust
32     /// let s = &String::new();
33     ///
34     /// let a: &String = &* s;
35     /// ```
36     ///
37     /// Use instead:
38     /// ```rust
39     /// # let s = &String::new();
40     /// let a: &String = s;
41     /// ```
42     #[clippy::version = "1.63.0"]
43     pub BORROW_DEREF_REF,
44     complexity,
45     "deref on an immutable reference returns the same type as itself"
46 }
47
48 declare_lint_pass!(BorrowDerefRef => [BORROW_DEREF_REF]);
49
50 impl LateLintPass<'_> for BorrowDerefRef {
51     fn check_expr(&mut self, cx: &LateContext<'_>, e: &rustc_hir::Expr<'_>) {
52         if_chain! {
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();
61             then{
62
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) {
66                         return;
67                     }
68
69                     // modification to `&mut &*x` is different from `&mut x`
70                     if matches!(deref_target.kind, ExprKind::Path(..)
71                                              | ExprKind::Field(..)
72                                              | ExprKind::Index(..)
73                                              | ExprKind::Unary(UnOp::Deref, ..))
74                      && matches!(parent_expr.kind, ExprKind::AddrOf(_, Mutability::Mut, _)) {
75                        return;
76                     }
77                 }
78
79                 span_lint_and_then(
80                     cx,
81                     BORROW_DEREF_REF,
82                     e.span,
83                     "deref on an immutable reference",
84                     |diag| {
85                         diag.span_suggestion(
86                             e.span,
87                             "if you would like to reborrow, try removing `&*`",
88                             snippet_opt(cx, deref_target.span).unwrap(),
89                             Applicability::MachineApplicable
90                         );
91
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, &[]) {
96                                 return;
97                             }
98                         }
99
100                         diag.span_suggestion(
101                             e.span,
102                             "if you would like to deref, try using `&**`",
103                             format!(
104                                 "&**{}",
105                                 &snippet_opt(cx, deref_target.span).unwrap(),
106                              ),
107                             Applicability::MaybeIncorrect
108                         );
109
110                     }
111                 );
112
113             }
114         }
115     }
116 }