]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/reference.rs
Auto merge of #6325 - flip1995:rustup, r=flip1995
[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 rpos = if *mutability == Mutability::Mut {
64                             macro_source.rfind("mut").expect("already checked this is a mutable reference") + "mut".len()
65                         } else {
66                             macro_source.rfind('&').expect("already checked this is a reference") + "&".len()
67                         };
68                         #[allow(clippy::cast_possible_truncation)]
69                         let span_after_ref = e.span.with_lo(BytePos(e.span.lo().0 + rpos as u32));
70                         let span = trim_leading_whitespaces(span_after_ref);
71                         snippet_with_applicability(cx, span, "_", &mut applicability)
72                     } else {
73                         snippet_with_applicability(cx, e.span, "_", &mut applicability)
74                     }
75                 } else {
76                     snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability)
77                 }.to_string();
78                 span_lint_and_sugg(
79                     cx,
80                     DEREF_ADDROF,
81                     e.span,
82                     "immediately dereferencing a reference",
83                     "try this",
84                     sugg,
85                     applicability,
86                 );
87             }
88         }
89     }
90 }
91
92 declare_clippy_lint! {
93     /// **What it does:** Checks for references in expressions that use
94     /// auto dereference.
95     ///
96     /// **Why is this bad?** The reference is a no-op and is automatically
97     /// dereferenced by the compiler and makes the code less clear.
98     ///
99     /// **Example:**
100     /// ```rust
101     /// struct Point(u32, u32);
102     /// let point = Point(30, 20);
103     /// let x = (&point).0;
104     /// ```
105     pub REF_IN_DEREF,
106     complexity,
107     "Use of reference in auto dereference expression."
108 }
109
110 declare_lint_pass!(RefInDeref => [REF_IN_DEREF]);
111
112 impl EarlyLintPass for RefInDeref {
113     fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
114         if_chain! {
115             if let ExprKind::Field(ref object, _) = e.kind;
116             if let ExprKind::Paren(ref parened) = object.kind;
117             if let ExprKind::AddrOf(_, _, ref inner) = parened.kind;
118             then {
119                 let mut applicability = Applicability::MachineApplicable;
120                 span_lint_and_sugg(
121                     cx,
122                     REF_IN_DEREF,
123                     object.span,
124                     "creating a reference that is immediately dereferenced",
125                     "try this",
126                     snippet_with_applicability(cx, inner.span, "_", &mut applicability).to_string(),
127                     applicability,
128                 );
129             }
130         }
131     }
132 }