]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/redundant_slicing.rs
Auto merge of #103116 - TaKO8Ki:fix-103053, r=lcnr
[rust.git] / src / tools / clippy / clippy_lints / src / redundant_slicing.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::get_parent_expr;
3 use clippy_utils::source::snippet_with_context;
4 use clippy_utils::ty::{is_type_lang_item, peel_mid_ty_refs};
5 use if_chain::if_chain;
6 use rustc_ast::util::parser::PREC_PREFIX;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BorrowKind, Expr, ExprKind, LangItem, Mutability};
9 use rustc_lint::{LateContext, LateLintPass, Lint};
10 use rustc_middle::ty::adjustment::{Adjust, AutoBorrow, AutoBorrowMutability};
11 use rustc_middle::ty::subst::GenericArg;
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13
14 use std::iter;
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Checks for redundant slicing expressions which use the full range, and
19     /// do not change the type.
20     ///
21     /// ### Why is this bad?
22     /// It unnecessarily adds complexity to the expression.
23     ///
24     /// ### Known problems
25     /// If the type being sliced has an implementation of `Index<RangeFull>`
26     /// that actually changes anything then it can't be removed. However, this would be surprising
27     /// to people reading the code and should have a note with it.
28     ///
29     /// ### Example
30     /// ```ignore
31     /// fn get_slice(x: &[u32]) -> &[u32] {
32     ///     &x[..]
33     /// }
34     /// ```
35     /// Use instead:
36     /// ```ignore
37     /// fn get_slice(x: &[u32]) -> &[u32] {
38     ///     x
39     /// }
40     /// ```
41     #[clippy::version = "1.51.0"]
42     pub REDUNDANT_SLICING,
43     complexity,
44     "redundant slicing of the whole range of a type"
45 }
46
47 declare_clippy_lint! {
48     /// ### What it does
49     /// Checks for slicing expressions which are equivalent to dereferencing the
50     /// value.
51     ///
52     /// ### Why is this bad?
53     /// Some people may prefer to dereference rather than slice.
54     ///
55     /// ### Example
56     /// ```rust
57     /// let vec = vec![1, 2, 3];
58     /// let slice = &vec[..];
59     /// ```
60     /// Use instead:
61     /// ```rust
62     /// let vec = vec![1, 2, 3];
63     /// let slice = &*vec;
64     /// ```
65     #[clippy::version = "1.61.0"]
66     pub DEREF_BY_SLICING,
67     restriction,
68     "slicing instead of dereferencing"
69 }
70
71 declare_lint_pass!(RedundantSlicing => [REDUNDANT_SLICING, DEREF_BY_SLICING]);
72
73 static REDUNDANT_SLICING_LINT: (&Lint, &str) = (REDUNDANT_SLICING, "redundant slicing of the whole range");
74 static DEREF_BY_SLICING_LINT: (&Lint, &str) = (DEREF_BY_SLICING, "slicing when dereferencing would work");
75
76 impl<'tcx> LateLintPass<'tcx> for RedundantSlicing {
77     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
78         if expr.span.from_expansion() {
79             return;
80         }
81
82         let ctxt = expr.span.ctxt();
83         if_chain! {
84             if let ExprKind::AddrOf(BorrowKind::Ref, mutability, addressee) = expr.kind;
85             if addressee.span.ctxt() == ctxt;
86             if let ExprKind::Index(indexed, range) = addressee.kind;
87             if is_type_lang_item(cx, cx.typeck_results().expr_ty_adjusted(range), LangItem::RangeFull);
88             then {
89                 let (expr_ty, expr_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(expr));
90                 let (indexed_ty, indexed_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(indexed));
91                 let parent_expr = get_parent_expr(cx, expr);
92                 let needs_parens_for_prefix = parent_expr.map_or(false, |parent| {
93                     parent.precedence().order() > PREC_PREFIX
94                 });
95                 let mut app = Applicability::MachineApplicable;
96
97                 let ((lint, msg), help, sugg) = if expr_ty == indexed_ty {
98                     if expr_ref_count > indexed_ref_count {
99                         // Indexing takes self by reference and can't return a reference to that
100                         // reference as it's a local variable. The only way this could happen is if
101                         // `self` contains a reference to the `Self` type. If this occurs then the
102                         // lint no longer applies as it's essentially a field access, which is not
103                         // redundant.
104                         return;
105                     }
106                     let deref_count = indexed_ref_count - expr_ref_count;
107
108                     let (lint, reborrow_str, help_str) = if mutability == Mutability::Mut {
109                         // The slice was used to reborrow the mutable reference.
110                         (DEREF_BY_SLICING_LINT, "&mut *", "reborrow the original value instead")
111                     } else if matches!(
112                         parent_expr,
113                         Some(Expr {
114                             kind: ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _),
115                             ..
116                         })
117                     ) || cx.typeck_results().expr_adjustments(expr).first().map_or(false, |a| {
118                         matches!(a.kind, Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })))
119                     }) {
120                         // The slice was used to make a temporary reference.
121                         (DEREF_BY_SLICING_LINT, "&*", "reborrow the original value instead")
122                     } else if deref_count != 0 {
123                         (DEREF_BY_SLICING_LINT, "", "dereference the original value instead")
124                     } else {
125                         (REDUNDANT_SLICING_LINT, "", "use the original value instead")
126                     };
127
128                     let snip = snippet_with_context(cx, indexed.span, ctxt, "..", &mut app).0;
129                     let sugg = if (deref_count != 0 || !reborrow_str.is_empty()) && needs_parens_for_prefix {
130                         format!("({reborrow_str}{}{snip})", "*".repeat(deref_count))
131                     } else {
132                         format!("{reborrow_str}{}{snip}", "*".repeat(deref_count))
133                     };
134
135                     (lint, help_str, sugg)
136                 } else if let Some(target_id) = cx.tcx.lang_items().deref_target() {
137                     if let Ok(deref_ty) = cx.tcx.try_normalize_erasing_regions(
138                         cx.param_env,
139                         cx.tcx.mk_projection(target_id, cx.tcx.mk_substs(iter::once(GenericArg::from(indexed_ty)))),
140                     ) {
141                         if deref_ty == expr_ty {
142                             let snip = snippet_with_context(cx, indexed.span, ctxt, "..", &mut app).0;
143                             let sugg = if needs_parens_for_prefix {
144                                 format!("(&{}{}*{snip})", mutability.prefix_str(), "*".repeat(indexed_ref_count))
145                             } else {
146                                 format!("&{}{}*{snip}", mutability.prefix_str(), "*".repeat(indexed_ref_count))
147                             };
148                             (DEREF_BY_SLICING_LINT, "dereference the original value instead", sugg)
149                         } else {
150                             return;
151                         }
152                     } else {
153                         return;
154                     }
155                 } else {
156                     return;
157                 };
158
159                 span_lint_and_sugg(
160                     cx,
161                     lint,
162                     expr.span,
163                     msg,
164                     help,
165                     sugg,
166                     app,
167                 );
168             }
169         }
170     }
171 }