]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/reference.rs
Fix lines that exceed max width manually
[rust.git] / clippy_lints / src / reference.rs
1 use syntax::ast::{Expr, ExprKind, UnOp};
2 use rustc::lint::*;
3 use utils::{snippet, span_lint_and_sugg};
4
5 /// **What it does:** Checks for usage of `*&` and `*&mut` in expressions.
6 ///
7 /// **Why is this bad?** Immediately dereferencing a reference is no-op and
8 /// makes the code less clear.
9 ///
10 /// **Known problems:** Multiple dereference/addrof pairs are not handled so
11 /// the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.
12 ///
13 /// **Example:**
14 /// ```rust
15 /// let a = f(*&mut b);
16 /// let c = *&d;
17 /// ```
18 declare_lint! {
19     pub DEREF_ADDROF,
20     Warn,
21     "use of `*&` or `*&mut` in an expression"
22 }
23
24 pub struct Pass;
25
26 impl LintPass for Pass {
27     fn get_lints(&self) -> LintArray {
28         lint_array!(DEREF_ADDROF)
29     }
30 }
31
32 fn without_parens(mut e: &Expr) -> &Expr {
33     while let ExprKind::Paren(ref child_e) = e.node {
34         e = child_e;
35     }
36     e
37 }
38
39 impl EarlyLintPass for Pass {
40     fn check_expr(&mut self, cx: &EarlyContext, e: &Expr) {
41         if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.node {
42             if let ExprKind::AddrOf(_, ref addrof_target) = without_parens(deref_target).node {
43                 span_lint_and_sugg(
44                     cx,
45                     DEREF_ADDROF,
46                     e.span,
47                     "immediately dereferencing a reference",
48                     "try this",
49                     format!("{}", snippet(cx, addrof_target.span, "_")),
50                 );
51             }
52         }
53     }
54 }