|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use rustc_errors::Applicability; |
| 3 | +use rustc_hir::{Expr, ExprKind, LangItem, Mutability, QPath}; |
| 4 | +use rustc_lint::{LateContext, LateLintPass}; |
| 5 | +use rustc_middle::ty::TyKind; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | +use rustc_span::symbol::sym; |
| 8 | + |
| 9 | +declare_clippy_lint! { |
| 10 | + /// ### What it does |
| 11 | + /// |
| 12 | + /// Detects if a full range slice reference is used instead of using the `.as_slice()` method. |
| 13 | + /// |
| 14 | + /// ### Why is this bad? |
| 15 | + /// |
| 16 | + /// Using the `some_value.as_slice()` method is more explicit then using `&some_value[..]` |
| 17 | + /// |
| 18 | + /// ### Example |
| 19 | + /// ```no_run |
| 20 | + /// let array: [u8; 4] = [0; 4]; |
| 21 | + /// let slice = &array[..]; |
| 22 | + /// ``` |
| 23 | + /// Use instead: |
| 24 | + /// ```no_run |
| 25 | + /// let array: [u8; 4] = [0; 4]; |
| 26 | + /// let slice = array.as_slice(); |
| 27 | + /// ``` |
| 28 | + #[clippy::version = "1.88.0"] |
| 29 | + pub MANUAL_AS_SLICE, |
| 30 | + nursery, |
| 31 | + "Use as slice instead of borrow full range." |
| 32 | +} |
| 33 | +declare_lint_pass!(ManualAsSlice => [MANUAL_AS_SLICE]); |
| 34 | + |
| 35 | +impl LateLintPass<'_> for ManualAsSlice { |
| 36 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 37 | + if let ExprKind::AddrOf(_, mutability, borrow) = expr.kind |
| 38 | + && let ExprKind::Index(value, index, index_span) = borrow.kind |
| 39 | + && let ExprKind::Struct(qpath, _, _) = index.kind |
| 40 | + && let QPath::LangItem(LangItem::RangeFull, _) = qpath |
| 41 | + { |
| 42 | + let sugg_tail = match mutability { |
| 43 | + Mutability::Not => ".as_slice()", |
| 44 | + Mutability::Mut => ".as_mut_slice()", |
| 45 | + }; |
| 46 | + |
| 47 | + let borrow_span = expr.span.until(borrow.span); |
| 48 | + let app = Applicability::MachineApplicable; |
| 49 | + |
| 50 | + match cx.typeck_results().expr_ty(value).kind() { |
| 51 | + TyKind::Array(_, _) | TyKind::Slice(_) => {}, |
| 52 | + TyKind::Ref(_, t, _) if let TyKind::Array(_, _) | TyKind::Slice(_) = t.kind() => {}, |
| 53 | + TyKind::Adt(adt, _) if cx.tcx.is_diagnostic_item(sym::Vec, adt.did()) => {}, |
| 54 | + _ => return, |
| 55 | + } |
| 56 | + |
| 57 | + span_lint_and_then(cx, MANUAL_AS_SLICE, expr.span, "using a full range slice", |diag| { |
| 58 | + diag.multipart_suggestion( |
| 59 | + "try", |
| 60 | + vec![(borrow_span, String::new()), (index_span, sugg_tail.to_string())], |
| 61 | + app, |
| 62 | + ); |
| 63 | + }); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments