Auto merge of #13117 - GuillaumeGomez:fix-single_element_loop-suggestion, r=Alexendoo

Fix wrong suggestion for `single_element_loop` where parens were missing

Fixes https://github.com/rust-lang/rust-clippy/issues/12782.

changelog: Fix missing parens in `single_element_loop` suggestion
This commit is contained in:
bors 2024-07-18 12:53:59 +00:00
commit bc2feea519
4 changed files with 37 additions and 3 deletions

View file

@ -5,7 +5,7 @@ use clippy_utils::visitors::contains_break_or_continue;
use rustc_ast::util::parser::PREC_PREFIX;
use rustc_ast::Mutability;
use rustc_errors::Applicability;
use rustc_hir::{is_range_literal, BorrowKind, Expr, ExprKind, Pat};
use rustc_hir::{is_range_literal, BorrowKind, Expr, ExprKind, Pat, PatKind};
use rustc_lint::LateContext;
use rustc_span::edition::Edition;
use rustc_span::sym;
@ -70,7 +70,10 @@ pub(super) fn check<'tcx>(
&& !contains_break_or_continue(body)
{
let mut applicability = Applicability::MachineApplicable;
let pat_snip = snippet_with_applicability(cx, pat.span, "..", &mut applicability);
let mut pat_snip = snippet_with_applicability(cx, pat.span, "..", &mut applicability);
if matches!(pat.kind, PatKind::Or(..)) {
pat_snip = format!("({pat_snip})").into();
}
let mut arg_snip = snippet_with_applicability(cx, arg_expression.span, "..", &mut applicability);
let mut block_str = snippet_with_applicability(cx, block.span, "..", &mut applicability).into_owned();
block_str.remove(0);

View file

@ -57,4 +57,12 @@ fn main() {
}
};
}
// Should lint with correct suggestion (issue #12782)
let res_void: Result<bool, bool> = Ok(true);
{
let (Ok(mut _x) | Err(mut _x)) = res_void;
let ptr: *const bool = std::ptr::null();
}
}

View file

@ -54,4 +54,11 @@ fn main() {
}
};
}
// Should lint with correct suggestion (issue #12782)
let res_void: Result<bool, bool> = Ok(true);
for (Ok(mut _x) | Err(mut _x)) in [res_void] {
let ptr: *const bool = std::ptr::null();
}
}

View file

@ -83,5 +83,21 @@ LL + };
LL + }
|
error: aborting due to 7 previous errors
error: for loop over a single element
--> tests/ui/single_element_loop.rs:61:5
|
LL | / for (Ok(mut _x) | Err(mut _x)) in [res_void] {
LL | | let ptr: *const bool = std::ptr::null();
LL | | }
| |_____^
|
help: try
|
LL ~ {
LL + let (Ok(mut _x) | Err(mut _x)) = res_void;
LL + let ptr: *const bool = std::ptr::null();
LL + }
|
error: aborting due to 8 previous errors