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