diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 21534290d1291..30c2849ca7c42 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -399,21 +399,31 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { fake_reads: _, } => { let closure_id = closure_id.expect_local(); - let closure_def = if let Some((did, const_param_id)) = - ty::WithOptConstParam::try_lookup(closure_id, self.tcx) - { - ty::WithOptConstParam { did, const_param_did: Some(const_param_id) } - } else { - ty::WithOptConstParam::unknown(closure_id) - }; - let (closure_thir, expr) = self.tcx.thir_body(closure_def); - let closure_thir = &closure_thir.borrow(); - let hir_context = self.tcx.hir().local_def_id_to_hir_id(closure_id); - let mut closure_visitor = - UnsafetyVisitor { thir: closure_thir, hir_context, ..*self }; - closure_visitor.visit_expr(&closure_thir[expr]); - // Unsafe blocks can be used in closures, make sure to take it into account - self.safety_context = closure_visitor.safety_context; + let closure_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_id); + + // Closures in AnonConsts are handled separately to avoid cycles (issue #87414). + if !matches!( + self.tcx.hir().get(self.tcx.hir().enclosing_body_owner(closure_hir_id)), + hir::Node::AnonConst(_) + ) { + let closure_def = if let Some((did, const_param_id)) = + ty::WithOptConstParam::try_lookup(closure_id, self.tcx) + { + ty::WithOptConstParam { did, const_param_did: Some(const_param_id) } + } else { + ty::WithOptConstParam::unknown(closure_id) + }; + let (closure_thir, expr) = self.tcx.thir_body(closure_def); + let closure_thir = &closure_thir.borrow(); + let mut closure_visitor = UnsafetyVisitor { + thir: closure_thir, + hir_context: closure_hir_id, + ..*self + }; + closure_visitor.visit_expr(&closure_thir[expr]); + // Unsafe blocks can be used in closures, make sure to take it into account + self.safety_context = closure_visitor.safety_context; + } } ExprKind::Field { lhs, .. } => { let lhs = &self.thir[lhs]; @@ -597,11 +607,19 @@ pub fn check_unsafety<'tcx>(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam(tcx: TyCtxt<'tcx>, def: ty::WithOptConstParam() -> Box> { todo!() } + +fn foo() -> [(); { |x: u32| { x }; 4 }] { todo!() } +fn bar() { let _: [(); { |x: u32| { x }; 4 }]; } + +// This one should not cause any errors either: +unsafe fn unsf() {} +fn bad2() -> Box> { todo!() } + +fn main() {}