Skip to content

Commit 4a2ff35

Browse files
committed
Auto merge of #3832 - HarrisonMc555:use_last, r=flip1995
Implement "Use last" lint Closes #3673 This lint checks the use of `x.get(x.len() - 1)` and suggests `x.last()` (where `x` is a `Vec`). There's at least one more thing that needs to happen here. I believe I am correctly checking most of the scenarios and avoiding false positives. However, if different `Vec`s are used for the `x.get` and `y.len`, then it will emit a false positive. In other words, I need to check to make sure the `Vec`s are the same. Also, a lot of these commits were temporary and not helpful to the project history...am I supposed to squash on merge? If so, how do I do that? changelog: New lint: `get_last_with_len`
2 parents 2cc23a5 + 3271491 commit 4a2ff35

File tree

7 files changed

+183
-1
lines changed

7 files changed

+183
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,7 @@ All notable changes to this project will be documented in this file.
936936
[`for_loop_over_result`]: https://rust-lang.github.io/rust-clippy/master/index.html#for_loop_over_result
937937
[`forget_copy`]: https://rust-lang.github.io/rust-clippy/master/index.html#forget_copy
938938
[`forget_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#forget_ref
939+
[`get_last_with_len`]: https://rust-lang.github.io/rust-clippy/master/index.html#get_last_with_len
939940
[`get_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#get_unwrap
940941
[`identity_conversion`]: https://rust-lang.github.io/rust-clippy/master/index.html#identity_conversion
941942
[`identity_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#identity_op

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
99

10-
[There are 303 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
10+
[There are 304 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
1111

1212
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1313

clippy_lints/src/get_last_with_len.rs

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
//! lint on using `x.get(x.len() - 1)` instead of `x.last()`
2+
3+
use crate::utils::{match_type, paths, snippet_with_applicability, span_lint_and_sugg, SpanlessEq};
4+
use if_chain::if_chain;
5+
use rustc::hir::{BinOpKind, Expr, ExprKind};
6+
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7+
use rustc::{declare_lint_pass, declare_tool_lint};
8+
use rustc_errors::Applicability;
9+
use syntax::ast::LitKind;
10+
use syntax::source_map::Spanned;
11+
use syntax::symbol::Symbol;
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<'a, 'tcx> LateLintPass<'a, 'tcx> for GetLastWithLen {
48+
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
49+
if_chain! {
50+
// Is a method call
51+
if let ExprKind::MethodCall(ref path, _, ref args) = expr.node;
52+
53+
// Method name is "get"
54+
if path.ident.name == Symbol::intern("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.tables.expr_ty(struct_calling_on);
59+
if match_type(cx, struct_ty, &paths::VEC);
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.node;
71+
72+
// LHS of subtraction is "x.len()"
73+
if let ExprKind::MethodCall(arg_lhs_path, _, lhs_args) = &lhs.node;
74+
if arg_lhs_path.ident.name == Symbol::intern("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.node;
82+
if let LitKind::Int(rhs_value, ..) = rhs_lit.node;
83+
if rhs_value == 1;
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+
}

clippy_lints/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ pub mod fallible_impl_from;
186186
pub mod format;
187187
pub mod formatting;
188188
pub mod functions;
189+
pub mod get_last_with_len;
189190
pub mod identity_conversion;
190191
pub mod identity_op;
191192
pub mod if_not_else;
@@ -492,6 +493,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
492493
reg.register_late_lint_pass(box types::CharLitAsU8);
493494
reg.register_late_lint_pass(box vec::UselessVec);
494495
reg.register_late_lint_pass(box drop_bounds::DropBounds);
496+
reg.register_late_lint_pass(box get_last_with_len::GetLastWithLen);
495497
reg.register_late_lint_pass(box drop_forget_ref::DropForgetRef);
496498
reg.register_late_lint_pass(box empty_enum::EmptyEnum);
497499
reg.register_late_lint_pass(box types::AbsurdExtremeComparisons);
@@ -710,6 +712,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
710712
formatting::SUSPICIOUS_ELSE_FORMATTING,
711713
functions::NOT_UNSAFE_PTR_ARG_DEREF,
712714
functions::TOO_MANY_ARGUMENTS,
715+
get_last_with_len::GET_LAST_WITH_LEN,
713716
identity_conversion::IDENTITY_CONVERSION,
714717
identity_op::IDENTITY_OP,
715718
indexing_slicing::OUT_OF_BOUNDS_INDEXING,
@@ -981,6 +984,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry<'_>, conf: &Conf) {
981984
explicit_write::EXPLICIT_WRITE,
982985
format::USELESS_FORMAT,
983986
functions::TOO_MANY_ARGUMENTS,
987+
get_last_with_len::GET_LAST_WITH_LEN,
984988
identity_conversion::IDENTITY_CONVERSION,
985989
identity_op::IDENTITY_OP,
986990
int_plus_one::INT_PLUS_ONE,

tests/ui/get_last_with_len.fixed

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::get_last_with_len)]
4+
5+
fn dont_use_last() {
6+
let x = vec![2, 3, 5];
7+
let _ = x.last(); // ~ERROR Use x.last()
8+
}
9+
10+
fn indexing_two_from_end() {
11+
let x = vec![2, 3, 5];
12+
let _ = x.get(x.len() - 2);
13+
}
14+
15+
fn index_into_last() {
16+
let x = vec![2, 3, 5];
17+
let _ = x[x.len() - 1];
18+
}
19+
20+
fn use_last_with_different_vec_length() {
21+
let x = vec![2, 3, 5];
22+
let y = vec!['a', 'b', 'c'];
23+
let _ = x.get(y.len() - 1);
24+
}
25+
26+
fn main() {
27+
dont_use_last();
28+
indexing_two_from_end();
29+
index_into_last();
30+
use_last_with_different_vec_length();
31+
}

tests/ui/get_last_with_len.rs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::get_last_with_len)]
4+
5+
fn dont_use_last() {
6+
let x = vec![2, 3, 5];
7+
let _ = x.get(x.len() - 1); // ~ERROR Use x.last()
8+
}
9+
10+
fn indexing_two_from_end() {
11+
let x = vec![2, 3, 5];
12+
let _ = x.get(x.len() - 2);
13+
}
14+
15+
fn index_into_last() {
16+
let x = vec![2, 3, 5];
17+
let _ = x[x.len() - 1];
18+
}
19+
20+
fn use_last_with_different_vec_length() {
21+
let x = vec![2, 3, 5];
22+
let y = vec!['a', 'b', 'c'];
23+
let _ = x.get(y.len() - 1);
24+
}
25+
26+
fn main() {
27+
dont_use_last();
28+
indexing_two_from_end();
29+
index_into_last();
30+
use_last_with_different_vec_length();
31+
}

tests/ui/get_last_with_len.stderr

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
error: accessing last element with `x.get(x.len() - 1)`
2+
--> $DIR/get_last_with_len.rs:7:13
3+
|
4+
LL | let _ = x.get(x.len() - 1); // ~ERROR Use x.last()
5+
| ^^^^^^^^^^^^^^^^^^ help: try: `x.last()`
6+
|
7+
= note: `-D clippy::get-last-with-len` implied by `-D warnings`
8+
9+
error: aborting due to previous error
10+

0 commit comments

Comments
 (0)