1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::{is_integer_literal, SpanlessEq};
4 use rustc_errors::Applicability;
5 use rustc_hir::{BinOpKind, Expr, ExprKind};
6 use rustc_lint::LateContext;
8 use rustc_span::source_map::Spanned;
11 use super::GET_LAST_WITH_LEN;
13 pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, arg: &Expr<'_>) {
14 // Argument to "get" is a subtraction
15 if let ExprKind::Binary(
17 node: BinOpKind::Sub, ..
23 // LHS of subtraction is "x.len()"
24 && let ExprKind::MethodCall(lhs_path, lhs_recv, [], _) = &lhs.kind
25 && lhs_path.ident.name == sym::len
27 // RHS of subtraction is 1
28 && is_integer_literal(rhs, 1)
30 // check that recv == lhs_recv `recv.get(lhs_recv.len() - 1)`
31 && SpanlessEq::new(cx).eq_expr(recv, lhs_recv)
32 && !recv.can_have_side_effects()
34 let method = match cx.typeck_results().expr_ty_adjusted(recv).peel_refs().kind() {
35 ty::Adt(def, _) if cx.tcx.is_diagnostic_item(sym::VecDeque, def.did()) => "back",
36 ty::Slice(_) => "last",
40 let mut applicability = Applicability::MachineApplicable;
41 let recv_snippet = snippet_with_applicability(cx, recv.span, "_", &mut applicability);
47 &format!("accessing last element with `{recv_snippet}.get({recv_snippet}.len() - 1)`"),
49 format!("{recv_snippet}.{method}()"),