]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/reference.rs
Auto merge of #81993 - flip1995:clippyup, r=Manishearth
[rust.git] / clippy_lints / src / reference.rs
1 use crate::utils::sugg::Sugg;
2 use crate::utils::{in_macro, snippet_opt, snippet_with_applicability, span_lint_and_sugg};
3 use if_chain::if_chain;
4 use rustc_ast::ast::{Expr, ExprKind, Mutability, UnOp};
5 use rustc_errors::Applicability;
6 use rustc_lint::{EarlyContext, EarlyLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::BytePos;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for usage of `*&` and `*&mut` in expressions.
12     ///
13     /// **Why is this bad?** Immediately dereferencing a reference is no-op and
14     /// makes the code less clear.
15     ///
16     /// **Known problems:** Multiple dereference/addrof pairs are not handled so
17     /// the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.
18     ///
19     /// **Example:**
20     /// ```rust,ignore
21     /// // Bad
22     /// let a = f(*&mut b);
23     /// let c = *&d;
24     ///
25     /// // Good
26     /// let a = f(b);
27     /// let c = d;
28     /// ```
29     pub DEREF_ADDROF,
30     complexity,
31     "use of `*&` or `*&mut` in an expression"
32 }
33
34 declare_lint_pass!(DerefAddrOf => [DEREF_ADDROF]);
35
36 fn without_parens(mut e: &Expr) -> &Expr {
37     while let ExprKind::Paren(ref child_e) = e.kind {
38         e = child_e;
39     }
40     e
41 }
42
43 impl EarlyLintPass for DerefAddrOf {
44     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
45         if_chain! {
46             if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.kind;
47             if let ExprKind::AddrOf(_, ref mutability, ref addrof_target) = without_parens(deref_target).kind;
48             if !in_macro(addrof_target.span);
49             then {
50                 let mut applicability = Applicability::MachineApplicable;
51                 let sugg = if e.span.from_expansion() {
52                     if let Ok(macro_source) = cx.sess.source_map().span_to_snippet(e.span) {
53                         // Remove leading whitespace from the given span
54                         // e.g: ` $visitor` turns into `$visitor`
55                         let trim_leading_whitespaces = |span| {
56                             snippet_opt(cx, span).and_then(|snip| {
57                                 #[allow(clippy::cast_possible_truncation)]
58                                 snip.find(|c: char| !c.is_whitespace()).map(|pos| {
59                                     span.lo() + BytePos(pos as u32)
60                                 })
61                             }).map_or(span, |start_no_whitespace| e.span.with_lo(start_no_whitespace))
62                         };
63
64                         let mut generate_snippet = |pattern: &str| {
65                             #[allow(clippy::cast_possible_truncation)]
66                             macro_source.rfind(pattern).map(|pattern_pos| {
67                                 let rpos = pattern_pos + pattern.len();
68                                 let span_after_ref = e.span.with_lo(BytePos(e.span.lo().0 + rpos as u32));
69                                 let span = trim_leading_whitespaces(span_after_ref);
70                                 snippet_with_applicability(cx, span, "_", &mut applicability)
71                             })
72                         };
73
74                         if *mutability == Mutability::Mut {
75                             generate_snippet("mut")
76                         } else {
77                             generate_snippet("&")
78                         }
79                     } else {
80                         Some(snippet_with_applicability(cx, e.span, "_", &mut applicability))
81                     }
82                 } else {
83                     Some(snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability))
84                 };
85                 if let Some(sugg) = sugg {
86                     span_lint_and_sugg(
87                         cx,
88                         DEREF_ADDROF,
89                         e.span,
90                         "immediately dereferencing a reference",
91                         "try this",
92                         sugg.to_string(),
93                         applicability,
94                     );
95                 }
96             }
97         }
98     }
99 }
100
101 declare_clippy_lint! {
102     /// **What it does:** Checks for references in expressions that use
103     /// auto dereference.
104     ///
105     /// **Why is this bad?** The reference is a no-op and is automatically
106     /// dereferenced by the compiler and makes the code less clear.
107     ///
108     /// **Example:**
109     /// ```rust
110     /// struct Point(u32, u32);
111     /// let point = Point(30, 20);
112     /// let x = (&point).0;
113     /// ```
114     /// Use instead:
115     /// ```rust
116     /// # struct Point(u32, u32);
117     /// # let point = Point(30, 20);
118     /// let x = point.0;
119     /// ```
120     pub REF_IN_DEREF,
121     complexity,
122     "Use of reference in auto dereference expression."
123 }
124
125 declare_lint_pass!(RefInDeref => [REF_IN_DEREF]);
126
127 impl EarlyLintPass for RefInDeref {
128     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
129         if_chain! {
130             if let ExprKind::Field(ref object, _) = e.kind;
131             if let ExprKind::Paren(ref parened) = object.kind;
132             if let ExprKind::AddrOf(_, _, ref inner) = parened.kind;
133             then {
134                 let applicability = if inner.span.from_expansion() {
135                     Applicability::MaybeIncorrect
136                 } else {
137                     Applicability::MachineApplicable
138                 };
139                 let sugg = Sugg::ast(cx, inner, "_").maybe_par();
140                 span_lint_and_sugg(
141                     cx,
142                     REF_IN_DEREF,
143                     object.span,
144                     "creating a reference that is immediately dereferenced",
145                     "try this",
146                     sugg.to_string(),
147                     applicability,
148                 );
149             }
150         }
151     }
152 }