|
1 | 1 | use clippy_utils::diagnostics::span_lint_and_sugg; |
2 | | -use clippy_utils::source::snippet_with_applicability; |
| 2 | +use clippy_utils::source::snippet_with_context; |
3 | 3 | use clippy_utils::ty::is_type_lang_item; |
| 4 | +use clippy_utils::{get_parent_expr, in_macro}; |
4 | 5 | use if_chain::if_chain; |
5 | 6 | use rustc_errors::Applicability; |
6 | | -use rustc_hir::{Expr, ExprKind, LangItem}; |
7 | | -use rustc_lint::{LateContext, LateLintPass, LintContext}; |
8 | | -use rustc_middle::{lint::in_external_macro, ty::TyS}; |
| 7 | +use rustc_hir::{BorrowKind, Expr, ExprKind, LangItem, Mutability}; |
| 8 | +use rustc_lint::{LateContext, LateLintPass}; |
| 9 | +use rustc_middle::ty::TyS; |
9 | 10 | use rustc_session::{declare_lint_pass, declare_tool_lint}; |
10 | 11 |
|
11 | 12 | declare_clippy_lint! { |
@@ -40,26 +41,44 @@ declare_lint_pass!(RedundantSlicing => [REDUNDANT_SLICING]); |
40 | 41 |
|
41 | 42 | impl LateLintPass<'_> for RedundantSlicing { |
42 | 43 | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { |
43 | | - if in_external_macro(cx.sess(), expr.span) { |
| 44 | + if in_macro(expr.span) { |
44 | 45 | return; |
45 | 46 | } |
46 | 47 |
|
| 48 | + let ctxt = expr.span.ctxt(); |
47 | 49 | if_chain! { |
48 | | - if let ExprKind::AddrOf(_, _, addressee) = expr.kind; |
| 50 | + if let ExprKind::AddrOf(BorrowKind::Ref, mutability, addressee) = expr.kind; |
| 51 | + if addressee.span.ctxt() == ctxt; |
49 | 52 | if let ExprKind::Index(indexed, range) = addressee.kind; |
50 | 53 | if is_type_lang_item(cx, cx.typeck_results().expr_ty_adjusted(range), LangItem::RangeFull); |
51 | 54 | if TyS::same_type(cx.typeck_results().expr_ty(expr), cx.typeck_results().expr_ty(indexed)); |
52 | 55 | then { |
53 | 56 | let mut app = Applicability::MachineApplicable; |
54 | | - let hint = snippet_with_applicability(cx, indexed.span, "..", &mut app).into_owned(); |
| 57 | + let snip = snippet_with_context(cx, indexed.span, ctxt, "..", &mut app).0; |
| 58 | + |
| 59 | + let (reborrow_str, help_str) = if mutability == Mutability::Mut { |
| 60 | + // The slice was used to reborrow the mutable reference. |
| 61 | + ("&mut *", "reborrow the original value instead") |
| 62 | + } else if matches!( |
| 63 | + get_parent_expr(cx, expr), |
| 64 | + Some(Expr { |
| 65 | + kind: ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _), |
| 66 | + .. |
| 67 | + }) |
| 68 | + ) { |
| 69 | + // The slice was used to make a temporary reference. |
| 70 | + ("&*", "reborrow the original value instead") |
| 71 | + } else { |
| 72 | + ("", "use the original value instead") |
| 73 | + }; |
55 | 74 |
|
56 | 75 | span_lint_and_sugg( |
57 | 76 | cx, |
58 | 77 | REDUNDANT_SLICING, |
59 | 78 | expr.span, |
60 | 79 | "redundant slicing of the whole range", |
61 | | - "use the original slice instead", |
62 | | - hint, |
| 80 | + help_str, |
| 81 | + format!("{}{}", reborrow_str, snip), |
63 | 82 | app, |
64 | 83 | ); |
65 | 84 | } |
|
0 commit comments