]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/get_last_with_len.rs
Update lint documentation to use markdown headlines
[rust.git] / clippy_lints / src / get_last_with_len.rs
1 //! lint on using `x.get(x.len() - 1)` instead of `x.last()`
2
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;
14 use rustc_span::sym;
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Checks for using `x.get(x.len() - 1)` instead of
19     /// `x.last()`.
20     ///
21     /// ### Why is this bad?
22     /// Using `x.last()` is easier to read and has the same
23     /// result.
24     ///
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`.
28     ///
29     /// There is another lint (get_unwrap) that covers the case of using
30     /// `x.get(index).unwrap()` instead of `x[index]`.
31     ///
32     /// ### Example
33     /// ```rust
34     /// // Bad
35     /// let x = vec![2, 3, 5];
36     /// let last_element = x.get(x.len() - 1);
37     ///
38     /// // Good
39     /// let x = vec![2, 3, 5];
40     /// let last_element = x.last();
41     /// ```
42     pub GET_LAST_WITH_LEN,
43     complexity,
44     "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
45 }
46
47 declare_lint_pass!(GetLastWithLen => [GET_LAST_WITH_LEN]);
48
49 impl<'tcx> LateLintPass<'tcx> for GetLastWithLen {
50     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
51         if_chain! {
52             // Is a method call
53             if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
54
55             // Method name is "get"
56             if path.ident.name == sym!(get);
57
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);
62
63             // Argument to "get" is a subtraction
64             if let Some(get_index_arg) = args.get(1);
65             if let ExprKind::Binary(
66                 Spanned {
67                     node: BinOpKind::Sub,
68                     ..
69                 },
70                 lhs,
71                 rhs,
72             ) = &get_index_arg.kind;
73
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);
78
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);
81
82             // RHS of subtraction is 1
83             if let ExprKind::Lit(rhs_lit) = &rhs.kind;
84             if let LitKind::Int(1, ..) = rhs_lit.node;
85
86             then {
87                 let mut applicability = Applicability::MachineApplicable;
88                 let vec_name = snippet_with_applicability(
89                     cx,
90                     struct_calling_on.span, "vec",
91                     &mut applicability,
92                 );
93
94                 span_lint_and_sugg(
95                     cx,
96                     GET_LAST_WITH_LEN,
97                     expr.span,
98                     &format!("accessing last element with `{0}.get({0}.len() - 1)`", vec_name),
99                     "try",
100                     format!("{}.last()", vec_name),
101                     applicability,
102                 );
103             }
104         }
105     }
106 }