autofix for range_zip_with_len (#14136)

changelog: [`range_zip_with_len`]: add autofix
This commit is contained in:
dswij 2025-02-08 05:20:10 +00:00 committed by GitHub
commit 8cc596cf95
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 28 additions and 10 deletions

View file

@ -1,6 +1,7 @@
use clippy_utils::diagnostics::span_lint;
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet;
use clippy_utils::{SpanlessEq, higher, is_integer_const, is_trait_method};
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind, QPath};
use rustc_lint::LateContext;
use rustc_span::sym;
@ -20,14 +21,14 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, recv: &'
&& let ExprKind::Path(QPath::Resolved(_, len_path)) = len_recv.kind
&& SpanlessEq::new(cx).eq_path_segments(iter_path.segments, len_path.segments)
{
span_lint(
span_lint_and_sugg(
cx,
RANGE_ZIP_WITH_LEN,
expr.span,
format!(
"it is more idiomatic to use `{}.iter().enumerate()`",
snippet(cx, recv.span, "_")
),
"using `.zip()` with a range and `.len()`",
"try",
format!("{}.iter().enumerate()", snippet(cx, recv.span, "_")),
Applicability::MachineApplicable,
);
}
}

18
tests/ui/range.fixed Normal file
View file

@ -0,0 +1,18 @@
#![allow(clippy::useless_vec)]
#[warn(clippy::range_zip_with_len)]
fn main() {
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5];
let _x = v1.iter().enumerate();
//~^ ERROR: using `.zip()` with a range and `.len()`
let _y = v1.iter().zip(0..v2.len()); // No error
}
#[allow(unused)]
fn no_panic_with_fake_range_types() {
struct Range {
foo: i32,
}
let _ = Range { foo: 0 };
}

View file

@ -4,8 +4,7 @@ fn main() {
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5];
let _x = v1.iter().zip(0..v1.len());
//~^ ERROR: it is more idiomatic to use `v1.iter().enumerate()`
//~| NOTE: `-D clippy::range-zip-with-len` implied by `-D warnings`
//~^ ERROR: using `.zip()` with a range and `.len()`
let _y = v1.iter().zip(0..v2.len()); // No error
}

View file

@ -1,8 +1,8 @@
error: it is more idiomatic to use `v1.iter().enumerate()`
error: using `.zip()` with a range and `.len()`
--> tests/ui/range.rs:6:14
|
LL | let _x = v1.iter().zip(0..v1.len());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `v1.iter().enumerate()`
|
= note: `-D clippy::range-zip-with-len` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(clippy::range_zip_with_len)]`