|
1 |
| -use crate::utils::{in_macro, snippet_with_applicability, span_lint_and_sugg}; |
| 1 | +use crate::utils::{in_macro, snippet_opt, snippet_with_applicability, span_lint_and_sugg}; |
2 | 2 | use if_chain::if_chain;
|
3 |
| -use rustc_ast::ast::{Expr, ExprKind, UnOp}; |
| 3 | +use rustc_ast::ast::{Expr, ExprKind, UnOp, Mutability}; |
4 | 4 | use rustc_errors::Applicability;
|
5 | 5 | use rustc_lint::{EarlyContext, EarlyLintPass};
|
6 | 6 | use rustc_session::{declare_lint_pass, declare_tool_lint};
|
| 7 | +use rustc_span::BytePos; |
| 8 | +// use rustc_span::source_map::{BytePos, Span}; |
7 | 9 |
|
8 | 10 | declare_clippy_lint! {
|
9 | 11 | /// **What it does:** Checks for usage of `*&` and `*&mut` in expressions.
|
@@ -42,13 +44,37 @@ impl EarlyLintPass for DerefAddrOf {
|
42 | 44 | fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
|
43 | 45 | if_chain! {
|
44 | 46 | if let ExprKind::Unary(UnOp::Deref, ref deref_target) = e.kind;
|
45 |
| - if let ExprKind::AddrOf(_, _, ref addrof_target) = without_parens(deref_target).kind; |
| 47 | + if let ExprKind::AddrOf(_, ref mutability, ref addrof_target) = without_parens(deref_target).kind; |
46 | 48 | if !in_macro(addrof_target.span);
|
47 | 49 | then {
|
48 | 50 | let mut applicability = Applicability::MachineApplicable;
|
49 | 51 | let sugg = if e.span.from_expansion() {
|
50 |
| - let snip = snippet_with_applicability(cx, e.span, "_", &mut applicability); |
51 |
| - snip.trim_start_matches(|c| c == '&' || c == '*').to_string() |
| 52 | + if let Ok(macro_source) = cx.sess.source_map().span_to_snippet(e.span) { |
| 53 | + // Remove leading whitespace from the given span |
| 54 | + // e.g: ` $visitor` turns into `$visitor` |
| 55 | + let trim_leading_whitespaces = |span| { |
| 56 | + if let Some(start_no_whitespace) = snippet_opt(cx, span).and_then(|snip| { |
| 57 | + snip.find(|c: char| !c.is_whitespace()).map(|pos| { |
| 58 | + span.lo() + BytePos(pos as u32) |
| 59 | + }) |
| 60 | + }) { |
| 61 | + e.span.with_lo(start_no_whitespace) |
| 62 | + } else { |
| 63 | + span |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + let rpos = if *mutability == Mutability::Mut { |
| 68 | + macro_source.rfind("mut").expect("already checked this is a mutable reference") + "mut".len() |
| 69 | + } else { |
| 70 | + macro_source.rfind("&").expect("already checked this is a reference") + "&".len() |
| 71 | + }; |
| 72 | + let span_after_ref = e.span.with_lo(BytePos(e.span.lo().0 + rpos as u32)); |
| 73 | + let span = trim_leading_whitespaces(span_after_ref); |
| 74 | + snippet_with_applicability(cx, span, "_", &mut applicability).to_string() |
| 75 | + } else { |
| 76 | + snippet_with_applicability(cx, e.span, "_", &mut applicability).to_string() |
| 77 | + } |
52 | 78 | } else {
|
53 | 79 | snippet_with_applicability(cx, addrof_target.span, "_", &mut applicability).to_string()
|
54 | 80 | };
|
|
0 commit comments