1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::{snippet_opt, snippet_with_applicability};
3 use if_chain::if_chain;
4 use rustc_ast::ast::{Expr, ExprKind, Mutability, UnOp};
5 use rustc_errors::Applicability;
6 use rustc_lint::{EarlyContext, EarlyLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::BytePos;
10 declare_clippy_lint! {
12 /// Checks for usage of `*&` and `*&mut` in expressions.
14 /// ### Why is this bad?
15 /// Immediately dereferencing a reference is no-op and
16 /// makes the code less clear.
18 /// ### Known problems
19 /// Multiple dereference/addrof pairs are not handled so
20 /// the suggested fix for `x = **&&y` is `x = *&y`, which is still incorrect.
24 /// let a = f(*&mut b);
33 #[clippy::version = "pre 1.29.0"]
36 "use of `*&` or `*&mut` in an expression"
39 declare_lint_pass!(DerefAddrOf => [DEREF_ADDROF]);
41 fn without_parens(mut e: &Expr) -> &Expr {
42 while let ExprKind::Paren(ref child_e) = e.kind {
48 impl EarlyLintPass for DerefAddrOf {
49 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
51 if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.kind;
52 if let ExprKind::AddrOf(_, ref mutability, ref addrof_target) = without_parens(deref_target).kind;
53 if deref_target.span.ctxt() == e.span.ctxt();
54 if !addrof_target.span.from_expansion();
56 let mut applicability = Applicability::MachineApplicable;
57 let sugg = if e.span.from_expansion() {
58 if let Some(macro_source) = snippet_opt(cx, e.span) {
59 // Remove leading whitespace from the given span
60 // e.g: ` $visitor` turns into `$visitor`
61 let trim_leading_whitespaces = |span| {
62 snippet_opt(cx, span).and_then(|snip| {
63 #[expect(clippy::cast_possible_truncation)]
64 snip.find(|c: char| !c.is_whitespace()).map(|pos| {
65 span.lo() + BytePos(pos as u32)
67 }).map_or(span, |start_no_whitespace| e.span.with_lo(start_no_whitespace))
70 let mut generate_snippet = |pattern: &str| {
71 #[expect(clippy::cast_possible_truncation)]
72 macro_source.rfind(pattern).map(|pattern_pos| {
73 let rpos = pattern_pos + pattern.len();
74 let span_after_ref = e.span.with_lo(BytePos(e.span.lo().0 + rpos as u32));
75 let span = trim_leading_whitespaces(span_after_ref);
76 snippet_with_applicability(cx, span, "_", &mut applicability)
80 if *mutability == Mutability::Mut {
81 generate_snippet("mut")
86 Some(snippet_with_applicability(cx, e.span, "_", &mut applicability))
89 Some(snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability))
91 if let Some(sugg) = sugg {
96 "immediately dereferencing a reference",