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