]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/redundant_slicing.rs
Merge remote-tracking branch 'upstream/beta' into backport_remerge
[rust.git] / clippy_lints / src / redundant_slicing.rs
1 use if_chain::if_chain;
2 use rustc_errors::Applicability;
3 use rustc_hir::{Expr, ExprKind, LangItem};
4 use rustc_lint::{LateContext, LateLintPass, LintContext};
5 use rustc_middle::{lint::in_external_macro, ty::TyS};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 use crate::utils::{is_type_lang_item, snippet_with_applicability, span_lint_and_sugg};
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for redundant slicing expressions which use the full range, and
12     /// do not change the type.
13     ///
14     /// **Why is this bad?** It unnecessarily adds complexity to the expression.
15     ///
16     /// **Known problems:** If the type being sliced has an implementation of `Index<RangeFull>`
17     /// that actually changes anything then it can't be removed. However, this would be surprising
18     /// to people reading the code and should have a note with it.
19     ///
20     /// **Example:**
21     ///
22     /// ```ignore
23     /// fn get_slice(x: &[u32]) -> &[u32] {
24     ///     &x[..]
25     /// }
26     /// ```
27     /// Use instead:
28     /// ```ignore
29     /// fn get_slice(x: &[u32]) -> &[u32] {
30     ///     x
31     /// }
32     /// ```
33     pub REDUNDANT_SLICING,
34     complexity,
35     "redundant slicing of the whole range of a type"
36 }
37
38 declare_lint_pass!(RedundantSlicing => [REDUNDANT_SLICING]);
39
40 impl LateLintPass<'_> for RedundantSlicing {
41     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
42         if in_external_macro(cx.sess(), expr.span) {
43             return;
44         }
45
46         if_chain! {
47             if let ExprKind::AddrOf(_, _, addressee) = expr.kind;
48             if let ExprKind::Index(indexed, range) = addressee.kind;
49             if is_type_lang_item(cx, cx.typeck_results().expr_ty_adjusted(range), LangItem::RangeFull);
50             if TyS::same_type(cx.typeck_results().expr_ty(expr), cx.typeck_results().expr_ty(indexed));
51             then {
52                 let mut app = Applicability::MachineApplicable;
53                 let hint = snippet_with_applicability(cx, indexed.span, "..", &mut app).into_owned();
54
55                 span_lint_and_sugg(
56                     cx,
57                     REDUNDANT_SLICING,
58                     expr.span,
59                     "redundant slicing of the whole range",
60                     "use the original slice instead",
61                     hint,
62                     app,
63                 );
64             }
65         }
66     }
67 }