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