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