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