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