1 use crate::utils::{snippet_with_applicability, span_lint_and_sugg};
2 use if_chain::if_chain;
3 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
4 use rustc::{declare_lint_pass, declare_tool_lint};
5 use rustc_errors::Applicability;
6 use syntax::ast::{Expr, ExprKind, UnOp};
9 /// **What it does:** Checks for usage of `*&` and `*&mut` in expressions.
11 /// **Why is this bad?** Immediately dereferencing a reference is no-op and
12 /// makes the code less clear.
14 /// **Known problems:** Multiple dereference/addrof pairs are not handled so
15 /// the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.
19 /// let a = f(*&mut b);
24 "use of `*&` or `*&mut` in an expression"
27 declare_lint_pass!(DerefAddrOf => [DEREF_ADDROF]);
29 fn without_parens(mut e: &Expr) -> &Expr {
30 while let ExprKind::Paren(ref child_e) = e.node {
36 impl EarlyLintPass for DerefAddrOf {
37 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
39 if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.node;
40 if let ExprKind::AddrOf(_, ref addrof_target) = without_parens(deref_target).node;
42 let mut applicability = Applicability::MachineApplicable;
47 "immediately dereferencing a reference",
49 format!("{}", snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability)),
57 declare_clippy_lint! {
58 /// **What it does:** Checks for references in expressions that use
61 /// **Why is this bad?** The reference is a no-op and is automatically
62 /// dereferenced by the compiler and makes the code less clear.
66 /// struct Point(u32, u32);
67 /// let point = Foo(30, 20);
68 /// let x = (&point).x;
72 "Use of reference in auto dereference expression."
75 declare_lint_pass!(RefInDeref => [REF_IN_DEREF]);
77 impl EarlyLintPass for RefInDeref {
78 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
80 if let ExprKind::Field(ref object, _) = e.node;
81 if let ExprKind::Paren(ref parened) = object.node;
82 if let ExprKind::AddrOf(_, ref inner) = parened.node;
84 let mut applicability = Applicability::MachineApplicable;
89 "Creating a reference that is immediately dereferenced.",
91 snippet_with_applicability(cx, inner.span, "_", &mut applicability).to_string(),