|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::source::snippet_with_applicability; |
| 3 | +use rustc_errors::Applicability; |
| 4 | +use rustc_hir::{Expr, ExprKind, LangItem, Mutability, QPath}; |
| 5 | +use rustc_lint::{LateContext, LateLintPass}; |
| 6 | +use rustc_session::declare_lint_pass; |
| 7 | + |
| 8 | +declare_clippy_lint! { |
| 9 | + /// ### What it does |
| 10 | + /// |
| 11 | + /// Detects if a full range slice reference is used instead of using the `.as_slice()` method. |
| 12 | + /// |
| 13 | + /// ### Why is this bad? |
| 14 | + /// |
| 15 | + /// Using the `some_value.as_slice()` method is more explicit then using `&some_value[..]` |
| 16 | + /// |
| 17 | + /// ### Example |
| 18 | + /// ```no_run |
| 19 | + /// let array: [u8; 4] = [0; 4]; |
| 20 | + /// let slice = &array[..]; |
| 21 | + /// ``` |
| 22 | + /// Use instead: |
| 23 | + /// ```no_run |
| 24 | + /// let array: [u8; 4] = [0; 4]; |
| 25 | + /// let slice = array.as_slice(); |
| 26 | + /// ``` |
| 27 | + #[clippy::version = "1.88.0"] |
| 28 | + pub MANUAL_AS_SLICE, |
| 29 | + nursery, |
| 30 | + "Use as slice instead of borrow full range." |
| 31 | +} |
| 32 | +declare_lint_pass!(ManualAsSlice => [MANUAL_AS_SLICE]); |
| 33 | + |
| 34 | +impl LateLintPass<'_> for ManualAsSlice { |
| 35 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 36 | + if let ExprKind::AddrOf(_, mutability, borrow) = expr.kind |
| 37 | + && let ExprKind::Index(name, indexing, _) = borrow.kind |
| 38 | + && !name.span.from_expansion() |
| 39 | + && let ExprKind::Struct(qpath, _, _) = indexing.kind |
| 40 | + && let QPath::LangItem(LangItem::RangeFull, _) = qpath |
| 41 | + { |
| 42 | + let mut app = Applicability::MachineApplicable; |
| 43 | + let snippet = snippet_with_applicability(cx, name.span, "..", &mut app); |
| 44 | + |
| 45 | + let (msg, sugg) = match mutability { |
| 46 | + Mutability::Not => ( |
| 47 | + "use `.as_slice()` instead of full range slice", |
| 48 | + format!("{snippet}.as_slice()"), |
| 49 | + ), |
| 50 | + Mutability::Mut => ( |
| 51 | + "use `.as_mut_slice()` instead of full range slice", |
| 52 | + format!("{snippet}.as_mut_slice()"), |
| 53 | + ), |
| 54 | + }; |
| 55 | + |
| 56 | + span_lint_and_sugg(cx, MANUAL_AS_SLICE, expr.span, msg, "try", sugg, app); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments