1 use crate::utils::{in_macro, 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.kind {
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.kind;
40 if let ExprKind::AddrOf(_, ref addrof_target) = without_parens(deref_target).kind;
41 if !in_macro(addrof_target.span);
43 let mut applicability = Applicability::MachineApplicable;
48 "immediately dereferencing a reference",
50 format!("{}", snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability)),
58 declare_clippy_lint! {
59 /// **What it does:** Checks for references in expressions that use
62 /// **Why is this bad?** The reference is a no-op and is automatically
63 /// dereferenced by the compiler and makes the code less clear.
67 /// struct Point(u32, u32);
68 /// let point = Point(30, 20);
69 /// let x = (&point).0;
73 "Use of reference in auto dereference expression."
76 declare_lint_pass!(RefInDeref => [REF_IN_DEREF]);
78 impl EarlyLintPass for RefInDeref {
79 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
81 if let ExprKind::Field(ref object, _) = e.kind;
82 if let ExprKind::Paren(ref parened) = object.kind;
83 if let ExprKind::AddrOf(_, ref inner) = parened.kind;
85 let mut applicability = Applicability::MachineApplicable;
90 "Creating a reference that is immediately dereferenced.",
92 snippet_with_applicability(cx, inner.span, "_", &mut applicability).to_string(),