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_tool_lint, lint_array};
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"
29 impl LintPass for Pass {
30 fn get_lints(&self) -> LintArray {
31 lint_array!(DEREF_ADDROF)
34 fn name(&self) -> &'static str {
39 fn without_parens(mut e: &Expr) -> &Expr {
40 while let ExprKind::Paren(ref child_e) = e.node {
46 impl EarlyLintPass for Pass {
47 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
49 if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.node;
50 if let ExprKind::AddrOf(_, ref addrof_target) = without_parens(deref_target).node;
52 let mut applicability = Applicability::MachineApplicable;
57 "immediately dereferencing a reference",
59 format!("{}", snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability)),
67 declare_clippy_lint! {
68 /// **What it does:** Checks for references in expressions that use
71 /// **Why is this bad?** The reference is a no-op and is automatically
72 /// dereferenced by the compiler and makes the code less clear.
76 /// struct Point(u32, u32);
77 /// let point = Foo(30, 20);
78 /// let x = (&point).x;
82 "Use of reference in auto dereference expression."
87 impl LintPass for DerefPass {
88 fn get_lints(&self) -> LintArray {
89 lint_array!(REF_IN_DEREF)
92 fn name(&self) -> &'static str {
97 impl EarlyLintPass for DerefPass {
98 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
100 if let ExprKind::Field(ref object, _) = e.node;
101 if let ExprKind::Paren(ref parened) = object.node;
102 if let ExprKind::AddrOf(_, ref inner) = parened.node;
104 let mut applicability = Applicability::MachineApplicable;
109 "Creating a reference that is immediately dereferenced.",
111 snippet_with_applicability(cx, inner.span, "_", &mut applicability).to_string(),