Skip to content

Commit

Permalink
Auto merge of #12515 - bend-n:🦀, r=llogiq
Browse files Browse the repository at this point in the history
fix `for x in y unsafe { }`

fixes #12514

----

changelog: [`needless_for_each`]: unsafe block in for loop body suggestion
  • Loading branch information
bors committed May 2, 2024
2 parents 1325425 + a3ef100 commit a2bd02b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
16 changes: 14 additions & 2 deletions clippy_lints/src/needless_for_each.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use rustc_errors::Applicability;
use rustc_hir::intravisit::{walk_expr, Visitor};
use rustc_hir::{Closure, Expr, ExprKind, Stmt, StmtKind};
use rustc_hir::{Block, BlockCheckMode, Closure, Expr, ExprKind, Stmt, StmtKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass;
use rustc_span::{sym, Span, Symbol};
Expand Down Expand Up @@ -35,6 +35,16 @@ declare_clippy_lint! {
/// println!("{}", elem);
/// }
/// ```
///
/// ### Known Problems
/// When doing things such as:
/// ```ignore
/// let v = vec![0, 1, 2];
/// v.iter().for_each(|elem| unsafe {
/// libc::printf(c"%d\n".as_ptr(), elem);
/// });
/// ```
/// This lint will not trigger.
#[clippy::version = "1.53.0"]
pub NEEDLESS_FOR_EACH,
pedantic,
Expand Down Expand Up @@ -68,7 +78,9 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
// e.g. `v.iter().for_each(f)` is simpler and clearer than using `for` loop.
&& let ExprKind::Closure(&Closure { body, .. }) = for_each_arg.kind
&& let body = cx.tcx.hir().body(body)
&& let ExprKind::Block(..) = body.value.kind
// Skip the lint if the body is not safe, so as not to suggest `for … in … unsafe {}`
// and suggesting `for … in … { unsafe { } }` is a little ugly.
&& let ExprKind::Block(Block { rules: BlockCheckMode::DefaultBlock, .. }, ..) = body.value.kind
{
let mut ret_collector = RetCollector::default();
ret_collector.visit_expr(body.value);
Expand Down
4 changes: 4 additions & 0 deletions tests/ui/needless_for_each_fixable.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ fn should_not_lint() {
let _ = v.iter().for_each(|elem| {
acc += elem;
});
// `for_each` has a closure with an unsafe block.
v.iter().for_each(|elem| unsafe {
acc += elem;
});
}

fn main() {}
4 changes: 4 additions & 0 deletions tests/ui/needless_for_each_fixable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ fn should_not_lint() {
let _ = v.iter().for_each(|elem| {
acc += elem;
});
// `for_each` has a closure with an unsafe block.
v.iter().for_each(|elem| unsafe {
acc += elem;
});
}

fn main() {}

0 comments on commit a2bd02b

Please sign in to comment.