]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/get_last_with_len.rs
Auto merge of #6907 - camsteffen:ty-utils, r=flip1995
[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 crate::utils::{snippet_with_applicability, span_lint_and_sugg, SpanlessEq};
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use if_chain::if_chain;
6 use rustc_ast::ast::LitKind;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Expr, ExprKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::source_map::Spanned;
12 use rustc_span::sym;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for using `x.get(x.len() - 1)` instead of
16     /// `x.last()`.
17     ///
18     /// **Why is this bad?** Using `x.last()` is easier to read and has the same
19     /// result.
20     ///
21     /// Note that using `x[x.len() - 1]` is semantically different from
22     /// `x.last()`.  Indexing into the array will panic on out-of-bounds
23     /// accesses, while `x.get()` and `x.last()` will return `None`.
24     ///
25     /// There is another lint (get_unwrap) that covers the case of using
26     /// `x.get(index).unwrap()` instead of `x[index]`.
27     ///
28     /// **Known problems:** None.
29     ///
30     /// **Example:**
31     ///
32     /// ```rust
33     /// // Bad
34     /// let x = vec![2, 3, 5];
35     /// let last_element = x.get(x.len() - 1);
36     ///
37     /// // Good
38     /// let x = vec![2, 3, 5];
39     /// let last_element = x.last();
40     /// ```
41     pub GET_LAST_WITH_LEN,
42     complexity,
43     "Using `x.get(x.len() - 1)` when `x.last()` is correct and simpler"
44 }
45
46 declare_lint_pass!(GetLastWithLen => [GET_LAST_WITH_LEN]);
47
48 impl<'tcx> LateLintPass<'tcx> for GetLastWithLen {
49     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
50         if_chain! {
51             // Is a method call
52             if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind;
53
54             // Method name is "get"
55             if path.ident.name == sym!(get);
56
57             // Argument 0 (the struct we're calling the method on) is a vector
58             if let Some(struct_calling_on) = args.get(0);
59             let struct_ty = cx.typeck_results().expr_ty(struct_calling_on);
60             if is_type_diagnostic_item(cx, struct_ty, sym::vec_type);
61
62             // Argument to "get" is a subtraction
63             if let Some(get_index_arg) = args.get(1);
64             if let ExprKind::Binary(
65                 Spanned {
66                     node: BinOpKind::Sub,
67                     ..
68                 },
69                 lhs,
70                 rhs,
71             ) = &get_index_arg.kind;
72
73             // LHS of subtraction is "x.len()"
74             if let ExprKind::MethodCall(arg_lhs_path, _, lhs_args, _) = &lhs.kind;
75             if arg_lhs_path.ident.name == sym!(len);
76             if let Some(arg_lhs_struct) = lhs_args.get(0);
77
78             // The two vectors referenced (x in x.get(...) and in x.len())
79             if SpanlessEq::new(cx).eq_expr(struct_calling_on, arg_lhs_struct);
80
81             // RHS of subtraction is 1
82             if let ExprKind::Lit(rhs_lit) = &rhs.kind;
83             if let LitKind::Int(1, ..) = rhs_lit.node;
84
85             then {
86                 let mut applicability = Applicability::MachineApplicable;
87                 let vec_name = snippet_with_applicability(
88                     cx,
89                     struct_calling_on.span, "vec",
90                     &mut applicability,
91                 );
92
93                 span_lint_and_sugg(
94                     cx,
95                     GET_LAST_WITH_LEN,
96                     expr.span,
97                     &format!("accessing last element with `{0}.get({0}.len() - 1)`", vec_name),
98                     "try",
99                     format!("{}.last()", vec_name),
100                     applicability,
101                 );
102             }
103         }
104     }
105 }