1 use syntax::ast::{Expr, ExprKind, UnOp};
3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
5 use crate::utils::{snippet, span_lint_and_sugg};
7 /// **What it does:** Checks for usage of `*&` and `*&mut` in expressions.
9 /// **Why is this bad?** Immediately dereferencing a reference is no-op and
10 /// makes the code less clear.
12 /// **Known problems:** Multiple dereference/addrof pairs are not handled so
13 /// the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.
17 /// let a = f(*&mut b);
20 declare_clippy_lint! {
23 "use of `*&` or `*&mut` in an expression"
28 impl LintPass for Pass {
29 fn get_lints(&self) -> LintArray {
30 lint_array!(DEREF_ADDROF)
34 fn without_parens(mut e: &Expr) -> &Expr {
35 while let ExprKind::Paren(ref child_e) = e.node {
41 impl EarlyLintPass for Pass {
42 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
44 if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.node;
45 if let ExprKind::AddrOf(_, ref addrof_target) = without_parens(deref_target).node;
51 "immediately dereferencing a reference",
53 format!("{}", snippet(cx, addrof_target.span, "_")),
60 /// **What it does:** Checks for references in expressions that use
63 /// **Why is this bad?** The reference is a no-op and is automatically
64 /// dereferenced by the compiler and makes the code less clear.
68 /// struct Point(u32, u32);
69 /// let point = Foo(30, 20);
70 /// let x = (&point).x;
72 declare_clippy_lint! {
75 "Use of reference in auto dereference expression."
80 impl LintPass for DerefPass {
81 fn get_lints(&self) -> LintArray {
82 lint_array!(REF_IN_DEREF)
86 impl EarlyLintPass for DerefPass {
87 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
89 if let ExprKind::Field(ref object, ref field_name) = e.node;
90 if let ExprKind::Paren(ref parened) = object.node;
91 if let ExprKind::AddrOf(_, ref inner) = parened.node;
97 "Creating a reference that is immediately dereferenced.",
101 snippet(cx, inner.span, "_"),
102 snippet(cx, field_name.span, "_")