1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use crate::rustc_errors::Applicability;
14 use crate::syntax::ast::{Expr, ExprKind, UnOp};
15 use crate::utils::{snippet_with_applicability, span_lint_and_sugg};
16 use if_chain::if_chain;
18 /// **What it does:** Checks for usage of `*&` and `*&mut` in expressions.
20 /// **Why is this bad?** Immediately dereferencing a reference is no-op and
21 /// makes the code less clear.
23 /// **Known problems:** Multiple dereference/addrof pairs are not handled so
24 /// the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.
28 /// let a = f(*&mut b);
31 declare_clippy_lint! {
34 "use of `*&` or `*&mut` in an expression"
39 impl LintPass for Pass {
40 fn get_lints(&self) -> LintArray {
41 lint_array!(DEREF_ADDROF)
45 fn without_parens(mut e: &Expr) -> &Expr {
46 while let ExprKind::Paren(ref child_e) = e.node {
52 impl EarlyLintPass for Pass {
53 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
55 if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.node;
56 if let ExprKind::AddrOf(_, ref addrof_target) = without_parens(deref_target).node;
58 let mut applicability = Applicability::MachineApplicable;
63 "immediately dereferencing a reference",
65 format!("{}", snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability)),
73 /// **What it does:** Checks for references in expressions that use
76 /// **Why is this bad?** The reference is a no-op and is automatically
77 /// dereferenced by the compiler and makes the code less clear.
81 /// struct Point(u32, u32);
82 /// let point = Foo(30, 20);
83 /// let x = (&point).x;
85 declare_clippy_lint! {
88 "Use of reference in auto dereference expression."
93 impl LintPass for DerefPass {
94 fn get_lints(&self) -> LintArray {
95 lint_array!(REF_IN_DEREF)
99 impl EarlyLintPass for DerefPass {
100 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
102 if let ExprKind::Field(ref object, ref field_name) = e.node;
103 if let ExprKind::Paren(ref parened) = object.node;
104 if let ExprKind::AddrOf(_, ref inner) = parened.node;
106 let mut applicability = Applicability::MachineApplicable;
111 "Creating a reference that is immediately dereferenced.",
115 snippet_with_applicability(cx, inner.span, "_", &mut applicability),
116 snippet_with_applicability(cx, field_name.span, "_", &mut applicability)