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.
10 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use crate::rustc_errors::Applicability;
13 use crate::syntax::ast::{Expr, ExprKind, UnOp};
14 use crate::utils::{snippet_with_applicability, span_lint_and_sugg};
15 use if_chain::if_chain;
17 /// **What it does:** Checks for usage of `*&` and `*&mut` in expressions.
19 /// **Why is this bad?** Immediately dereferencing a reference is no-op and
20 /// makes the code less clear.
22 /// **Known problems:** Multiple dereference/addrof pairs are not handled so
23 /// the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.
27 /// let a = f(*&mut b);
30 declare_clippy_lint! {
33 "use of `*&` or `*&mut` in an expression"
38 impl LintPass for Pass {
39 fn get_lints(&self) -> LintArray {
40 lint_array!(DEREF_ADDROF)
44 fn without_parens(mut e: &Expr) -> &Expr {
45 while let ExprKind::Paren(ref child_e) = e.node {
51 impl EarlyLintPass for Pass {
52 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
54 if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.node;
55 if let ExprKind::AddrOf(_, ref addrof_target) = without_parens(deref_target).node;
57 let mut applicability = Applicability::MachineApplicable;
62 "immediately dereferencing a reference",
64 format!("{}", snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability)),
72 /// **What it does:** Checks for references in expressions that use
75 /// **Why is this bad?** The reference is a no-op and is automatically
76 /// dereferenced by the compiler and makes the code less clear.
80 /// struct Point(u32, u32);
81 /// let point = Foo(30, 20);
82 /// let x = (&point).x;
84 declare_clippy_lint! {
87 "Use of reference in auto dereference expression."
92 impl LintPass for DerefPass {
93 fn get_lints(&self) -> LintArray {
94 lint_array!(REF_IN_DEREF)
98 impl EarlyLintPass for DerefPass {
99 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
101 if let ExprKind::Field(ref object, ref field_name) = e.node;
102 if let ExprKind::Paren(ref parened) = object.node;
103 if let ExprKind::AddrOf(_, ref inner) = parened.node;
105 let mut applicability = Applicability::MachineApplicable;
110 "Creating a reference that is immediately dereferenced.",
114 snippet_with_applicability(cx, inner.span, "_", &mut applicability),
115 snippet_with_applicability(cx, field_name.span, "_", &mut applicability)