Skip to content

Properly analyze captures from unsafe binders #141433

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions compiler/rustc_hir_typeck/src/expr_use_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use hir::Expr;
use hir::def::DefKind;
use hir::pat_util::EnumerateAndAdjustIterator as _;
use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
use rustc_ast::UnsafeBinderCastKind;
use rustc_data_structures::fx::FxIndexMap;
use rustc_hir::def::{CtorOf, Res};
use rustc_hir::def_id::LocalDefId;
Expand Down Expand Up @@ -1393,10 +1394,18 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx
self.cat_res(expr.hir_id, expr.span, expr_ty, res)
}

// both type ascription and unsafe binder casts don't affect
// the place-ness of the subexpression.
// type ascription doesn't affect the place-ness of the subexpression.
hir::ExprKind::Type(e, _) => self.cat_expr(e),
hir::ExprKind::UnsafeBinderCast(_, e, _) => self.cat_expr(e),

hir::ExprKind::UnsafeBinderCast(UnsafeBinderCastKind::Unwrap, e, _) => {
let base = self.cat_expr(e)?;
Ok(self.cat_projection(
expr.hir_id,
base,
expr_ty,
ProjectionKind::UnwrapUnsafeBinder,
))
}

hir::ExprKind::AddrOf(..)
| hir::ExprKind::Call(..)
Expand Down Expand Up @@ -1427,6 +1436,7 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx
| hir::ExprKind::Repeat(..)
| hir::ExprKind::InlineAsm(..)
| hir::ExprKind::OffsetOf(..)
| hir::ExprKind::UnsafeBinderCast(UnsafeBinderCastKind::Wrap, ..)
| hir::ExprKind::Err(_) => Ok(self.cat_rvalue(expr.hir_id, expr_ty)),
}
}
Expand Down
8 changes: 6 additions & 2 deletions compiler/rustc_hir_typeck/src/upvar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn is_field<'a>(p: &&Projection<'a>) -> bool {
match p.kind {
ProjectionKind::Field(_, _) => true,
ProjectionKind::Deref | ProjectionKind::OpaqueCast => false,
ProjectionKind::Deref
| ProjectionKind::OpaqueCast
| ProjectionKind::UnwrapUnsafeBinder => false,
p @ (ProjectionKind::Subslice | ProjectionKind::Index) => {
bug!("ProjectionKind {:?} was unexpected", p)
}
Expand Down Expand Up @@ -2197,7 +2199,8 @@ fn restrict_capture_precision(
}
ProjectionKind::Deref => {}
ProjectionKind::OpaqueCast => {}
ProjectionKind::Field(..) => {} // ignore
ProjectionKind::Field(..) => {}
ProjectionKind::UnwrapUnsafeBinder => {}
}
}

Expand Down Expand Up @@ -2268,6 +2271,7 @@ fn construct_place_string<'tcx>(tcx: TyCtxt<'_>, place: &Place<'tcx>) -> String
ProjectionKind::Index => String::from("Index"),
ProjectionKind::Subslice => String::from("Subslice"),
ProjectionKind::OpaqueCast => String::from("OpaqueCast"),
ProjectionKind::UnwrapUnsafeBinder => String::from("UnwrapUnsafeBinder"),
};
if i != 0 {
projections_str.push(',');
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_middle/src/hir/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ pub enum ProjectionKind {
///
/// This is unused if `-Znext-solver` is enabled.
OpaqueCast,

/// `unwrap_binder!(expr)`
UnwrapUnsafeBinder,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable, HashStable)]
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_mir_build/src/builder/expr/as_place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,9 @@ fn strip_prefix<'tcx>(
HirProjectionKind::OpaqueCast => {
assert_matches!(iter.next(), Some(ProjectionElem::OpaqueCast(..)));
}
HirProjectionKind::UnwrapUnsafeBinder => {
assert_matches!(iter.next(), Some(ProjectionElem::UnwrapUnsafeBinder(..)));
}
HirProjectionKind::Index | HirProjectionKind::Subslice => {
bug!("unexpected projection kind: {:?}", projection);
}
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_mir_build/src/thir/cx/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1220,6 +1220,9 @@ impl<'tcx> ThirBuildCx<'tcx> {
HirProjectionKind::OpaqueCast => {
ExprKind::Use { source: self.thir.exprs.push(captured_place_expr) }
}
HirProjectionKind::UnwrapUnsafeBinder => ExprKind::PlaceUnwrapUnsafeBinder {
source: self.thir.exprs.push(captured_place_expr),
},
HirProjectionKind::Index | HirProjectionKind::Subslice => {
// We don't capture these projections, so we can ignore them here
continue;
Expand Down
2 changes: 2 additions & 0 deletions src/tools/clippy/clippy_utils/src/sugg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,8 @@ impl<'tcx> Delegate<'tcx> for DerefDelegate<'_, 'tcx> {
ProjectionKind::Subslice |
// Doesn't have surface syntax. Only occurs in patterns.
ProjectionKind::OpaqueCast => (),
// Only occurs in closure captures.
ProjectionKind::UnwrapUnsafeBinder => (),
ProjectionKind::Deref => {
// Explicit derefs are typically handled later on, but
// some items do not need explicit deref, such as array accesses,
Expand Down
21 changes: 21 additions & 0 deletions tests/ui/unsafe-binders/cat-projection.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//@ check-pass

#![feature(unsafe_binders)]
#![allow(incomplete_features)]

use std::unsafe_binder::unwrap_binder;

#[derive(Copy, Clone)]
pub struct S([usize; 8]);

// Regression test for <https://github.com/rust-lang/rust/issues/141418>.
pub fn by_value(x: unsafe<'a> S) -> usize {
unsafe { (|| unwrap_binder!(x).0[0])() }
}

// Regression test for <https://github.com/rust-lang/rust/issues/141417>.
pub fn by_ref(x: unsafe<'a> &'a S) -> usize {
unsafe { (|| unwrap_binder!(x).0[0])() }
}

fn main() {}
Loading