1 //! lint on using `x.get(x.len() - 1)` instead of `x.last()`
3 use clippy_utils::diagnostics::span_lint_and_sugg;
4 use clippy_utils::source::snippet_with_applicability;
5 use clippy_utils::ty::is_type_diagnostic_item;
6 use clippy_utils::SpanlessEq;
7 use if_chain::if_chain;
8 use rustc_ast::ast::LitKind;
9 use rustc_errors::Applicability;
10 use rustc_hir::{BinOpKind, Expr, ExprKind};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Spanned;
16 declare_clippy_lint! {
18 /// Checks for using `x.get(x.len() - 1)` instead of
21 /// ### Why is this bad?
22 /// Using `x.last()` is easier to read and has the same
25 /// Note that using `x[x.len() - 1]` is semantically different from
26 /// `x.last()`. Indexing into the array will panic on out-of-bounds
27 /// accesses, while `x.get()` and `x.last()` will return `None`.
29 /// There is another lint (get_unwrap) that covers the case of using
30 /// `x.get(index).unwrap()` instead of `x[index]`.
35 /// let x = vec![2, 3, 5];
36 /// let last_element = x.get(x.len() - 1);
39 /// let x = vec![2, 3, 5];
40 /// let last_element = x.last();
42 pub GET_LAST_WITH_LEN,
44 "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
47 declare_lint_pass!(GetLastWithLen => [GET_LAST_WITH_LEN]);
49 impl<'tcx> LateLintPass<'tcx> for GetLastWithLen {
50 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
53 if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
55 // Method name is "get"
56 if path.ident.name == sym!(get);
58 // Argument 0 (the struct we're calling the method on) is a vector
59 if let Some(struct_calling_on) = args.get(0);
60 let struct_ty = cx.typeck_results().expr_ty(struct_calling_on);
61 if is_type_diagnostic_item(cx, struct_ty, sym::vec_type);
63 // Argument to "get" is a subtraction
64 if let Some(get_index_arg) = args.get(1);
65 if let ExprKind::Binary(
72 ) = &get_index_arg.kind;
74 // LHS of subtraction is "x.len()"
75 if let ExprKind::MethodCall(arg_lhs_path, _, lhs_args, _) = &lhs.kind;
76 if arg_lhs_path.ident.name == sym::len;
77 if let Some(arg_lhs_struct) = lhs_args.get(0);
79 // The two vectors referenced (x in x.get(...) and in x.len())
80 if SpanlessEq::new(cx).eq_expr(struct_calling_on, arg_lhs_struct);
82 // RHS of subtraction is 1
83 if let ExprKind::Lit(rhs_lit) = &rhs.kind;
84 if let LitKind::Int(1, ..) = rhs_lit.node;
87 let mut applicability = Applicability::MachineApplicable;
88 let vec_name = snippet_with_applicability(
90 struct_calling_on.span, "vec",
98 &format!("accessing last element with `{0}.get({0}.len() - 1)`", vec_name),
100 format!("{}.last()", vec_name),