Skip to content

Commit ba8e792

Browse files
authored
Rollup merge of rust-lang#120950 - compiler-errors:miri-async-closurs, r=RalfJung,oli-obk
Fix async closures in CTFE First commit renames `is_coroutine_or_closure` into `is_closure_like`, because `is_coroutine_or_closure_or_coroutine_closure` seems confusing and long. Second commit fixes some forgotten cases where we want to handle `TyKind::CoroutineClosure` the same as closures and coroutines. The test exercises the change to `ValidityVisitor::aggregate_field_path_elem` which is the source of rust-lang#120946, but not the change to `UsedParamsNeedSubstVisitor`, though I feel like it's not that big of a deal. Let me know if you'd like for me to look into constructing a test for the latter, though I have no idea what it'd look like (we can't assert against `TooGeneric` anywhere?). Fixes rust-lang#120946 r? oli-obk cc `@RalfJung`
2 parents 7811a82 + 8781637 commit ba8e792

File tree

21 files changed

+86
-39
lines changed

21 files changed

+86
-39
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -3158,7 +3158,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
31583158
) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
31593159
// Define a fallback for when we can't match a closure.
31603160
let fallback = || {
3161-
let is_closure = self.infcx.tcx.is_closure_or_coroutine(self.mir_def_id().to_def_id());
3161+
let is_closure = self.infcx.tcx.is_closure_like(self.mir_def_id().to_def_id());
31623162
if is_closure {
31633163
None
31643164
} else {
@@ -3369,7 +3369,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
33693369
sig: ty::PolyFnSig<'tcx>,
33703370
) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
33713371
debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
3372-
let is_closure = self.infcx.tcx.is_closure_or_coroutine(did.to_def_id());
3372+
let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
33733373
let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
33743374
let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
33753375

compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
6767
local,
6868
projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)],
6969
} => {
70-
debug_assert!(is_closure_or_coroutine(
70+
debug_assert!(is_closure_like(
7171
Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty
7272
));
7373

@@ -126,9 +126,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
126126
{
127127
item_msg = access_place_desc;
128128
debug_assert!(self.body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty.is_ref());
129-
debug_assert!(is_closure_or_coroutine(
130-
the_place_err.ty(self.body, self.infcx.tcx).ty
131-
));
129+
debug_assert!(is_closure_like(the_place_err.ty(self.body, self.infcx.tcx).ty));
132130

133131
reason = if self.is_upvar_field_projection(access_place.as_ref()).is_some() {
134132
", as it is a captured variable in a `Fn` closure".to_string()
@@ -389,7 +387,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
389387
local,
390388
projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)],
391389
} => {
392-
debug_assert!(is_closure_or_coroutine(
390+
debug_assert!(is_closure_like(
393391
Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty
394392
));
395393

@@ -1474,7 +1472,8 @@ fn suggest_ampmut<'tcx>(
14741472
}
14751473
}
14761474

1477-
fn is_closure_or_coroutine(ty: Ty<'_>) -> bool {
1475+
/// If the type is a `Coroutine`, `Closure`, or `CoroutineClosure`
1476+
fn is_closure_like(ty: Ty<'_>) -> bool {
14781477
ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure()
14791478
}
14801479

compiler/rustc_borrowck/src/type_check/input_output.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
2929
pub(super) fn check_signature_annotation(&mut self, body: &Body<'tcx>) {
3030
let mir_def_id = body.source.def_id().expect_local();
3131

32-
if !self.tcx().is_closure_or_coroutine(mir_def_id.to_def_id()) {
32+
if !self.tcx().is_closure_like(mir_def_id.to_def_id()) {
3333
return;
3434
}
3535

compiler/rustc_codegen_llvm/src/attributes.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -479,7 +479,7 @@ pub fn from_fn_attrs<'ll, 'tcx>(
479479
// `+multivalue` feature because the purpose of the wasm abi is to match
480480
// the WebAssembly specification, which has this feature. This won't be
481481
// needed when LLVM enables this `multivalue` feature by default.
482-
if !cx.tcx.is_closure_or_coroutine(instance.def_id()) {
482+
if !cx.tcx.is_closure_like(instance.def_id()) {
483483
let abi = cx.tcx.fn_sig(instance.def_id()).skip_binder().abi();
484484
if abi == Abi::Wasm {
485485
function_features.push("+multivalue".to_string());

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
229229
}
230230
sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
231231
sym::track_caller => {
232-
let is_closure = tcx.is_closure_or_coroutine(did.to_def_id());
232+
let is_closure = tcx.is_closure_like(did.to_def_id());
233233

234234
if !is_closure
235235
&& let Some(fn_sig) = fn_sig()
@@ -274,7 +274,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
274274
}
275275
}
276276
sym::target_feature => {
277-
if !tcx.is_closure_or_coroutine(did.to_def_id())
277+
if !tcx.is_closure_like(did.to_def_id())
278278
&& let Some(fn_sig) = fn_sig()
279279
&& fn_sig.skip_binder().unsafety() == hir::Unsafety::Normal
280280
{
@@ -529,7 +529,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
529529
// would result in this closure being compiled without the inherited target features, but this
530530
// is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
531531
if tcx.features().target_feature_11
532-
&& tcx.is_closure_or_coroutine(did.to_def_id())
532+
&& tcx.is_closure_like(did.to_def_id())
533533
&& codegen_fn_attrs.inline != InlineAttr::Always
534534
{
535535
let owner_id = tcx.parent(did.to_def_id());

compiler/rustc_const_eval/src/interpret/util.rs

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ where
3434
match *ty.kind() {
3535
ty::Param(_) => ControlFlow::Break(FoundParam),
3636
ty::Closure(def_id, args)
37+
| ty::CoroutineClosure(def_id, args, ..)
3738
| ty::Coroutine(def_id, args, ..)
3839
| ty::FnDef(def_id, args) => {
3940
let instance = ty::InstanceDef::Item(def_id);

compiler/rustc_const_eval/src/interpret/validity.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -240,8 +240,8 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, '
240240

241241
// Now we know we are projecting to a field, so figure out which one.
242242
match layout.ty.kind() {
243-
// coroutines and closures.
244-
ty::Closure(def_id, _) | ty::Coroutine(def_id, _) => {
243+
// coroutines, closures, and coroutine-closures all have upvars that may be named.
244+
ty::Closure(def_id, _) | ty::Coroutine(def_id, _) | ty::CoroutineClosure(def_id, _) => {
245245
let mut name = None;
246246
// FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar
247247
// https://github.com/rust-lang/project-rfc-2229/issues/46

compiler/rustc_const_eval/src/transform/check_consts/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ impl<'mir, 'tcx> ConstCx<'mir, 'tcx> {
7272

7373
pub fn fn_sig(&self) -> PolyFnSig<'tcx> {
7474
let did = self.def_id().to_def_id();
75-
if self.tcx.is_closure_or_coroutine(did) {
75+
if self.tcx.is_closure_like(did) {
7676
let ty = self.tcx.type_of(did).instantiate_identity();
7777
let ty::Closure(_, args) = ty.kind() else { bug!("type_of closure not ty::Closure") };
7878
args.as_closure().sig()

compiler/rustc_hir/src/def.rs

+6
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,12 @@ pub enum DefKind {
116116
Impl {
117117
of_trait: bool,
118118
},
119+
/// A closure, coroutine, or coroutine-closure.
120+
///
121+
/// These are all represented with the same `ExprKind::Closure` in the AST and HIR,
122+
/// which makes it difficult to distinguish these during def collection. Therefore,
123+
/// we treat them all the same, and code which needs to distinguish them can match
124+
/// or `hir::ClosureKind` or `type_of`.
119125
Closure,
120126
}
121127

compiler/rustc_hir_typeck/src/check.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,7 @@ pub(super) fn check_fn<'a, 'tcx>(
9090
// ty.span == binding_span iff this is a closure parameter with no type ascription,
9191
// or if it's an implicit `self` parameter
9292
traits::SizedArgumentType(
93-
if ty_span == Some(param.span) && tcx.is_closure_or_coroutine(fn_def_id.into())
94-
{
93+
if ty_span == Some(param.span) && tcx.is_closure_like(fn_def_id.into()) {
9594
None
9695
} else {
9796
ty.map(|ty| ty.hir_id)

compiler/rustc_hir_typeck/src/gather_locals.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> {
153153
// ascription, or if it's an implicit `self` parameter
154154
traits::SizedArgumentType(
155155
if ty_span == ident.span
156-
&& self.fcx.tcx.is_closure_or_coroutine(self.fcx.body_id.into())
156+
&& self.fcx.tcx.is_closure_like(self.fcx.body_id.into())
157157
{
158158
None
159159
} else {

compiler/rustc_middle/src/mir/pretty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,7 @@ fn write_mir_sig(tcx: TyCtxt<'_>, body: &Body<'_>, w: &mut dyn io::Write) -> io:
491491
let kind = tcx.def_kind(def_id);
492492
let is_function = match kind {
493493
DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(..) => true,
494-
_ => tcx.is_closure_or_coroutine(def_id),
494+
_ => tcx.is_closure_like(def_id),
495495
};
496496
match (kind, body.source.promoted) {
497497
(_, Some(i)) => write!(w, "{i:?} in ")?,

compiler/rustc_middle/src/ty/closure.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ pub struct ClosureTypeInfo<'tcx> {
197197
}
198198

199199
fn closure_typeinfo<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> ClosureTypeInfo<'tcx> {
200-
debug_assert!(tcx.is_closure_or_coroutine(def.to_def_id()));
200+
debug_assert!(tcx.is_closure_like(def.to_def_id()));
201201
let typeck_results = tcx.typeck(def);
202202
let user_provided_sig = typeck_results.user_provided_sigs[&def];
203203
let captures = typeck_results.closure_min_captures_flattened(def);
@@ -217,7 +217,7 @@ impl<'tcx> TyCtxt<'tcx> {
217217
}
218218

219219
pub fn closure_captures(self, def_id: LocalDefId) -> &'tcx [&'tcx ty::CapturedPlace<'tcx>] {
220-
if !self.is_closure_or_coroutine(def_id.to_def_id()) {
220+
if !self.is_closure_like(def_id.to_def_id()) {
221221
return &[];
222222
};
223223
self.closure_typeinfo(def_id).captures

compiler/rustc_middle/src/ty/instance.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -465,10 +465,7 @@ impl<'tcx> Instance<'tcx> {
465465
) -> Option<Instance<'tcx>> {
466466
debug!("resolve(def_id={:?}, args={:?})", def_id, args);
467467
// Use either `resolve_closure` or `resolve_for_vtable`
468-
assert!(
469-
!tcx.is_closure_or_coroutine(def_id),
470-
"Called `resolve_for_fn_ptr` on closure: {def_id:?}"
471-
);
468+
assert!(!tcx.is_closure_like(def_id), "Called `resolve_for_fn_ptr` on closure: {def_id:?}");
472469
Instance::resolve(tcx, param_env, def_id, args).ok().flatten().map(|mut resolved| {
473470
match resolved.def {
474471
InstanceDef::Item(def) if resolved.def.requires_caller_location(tcx) => {
@@ -530,7 +527,7 @@ impl<'tcx> Instance<'tcx> {
530527
})
531528
)
532529
{
533-
if tcx.is_closure_or_coroutine(def) {
530+
if tcx.is_closure_like(def) {
534531
debug!(" => vtable fn pointer created for closure with #[track_caller]: {:?} for method {:?} {:?}",
535532
def, def_id, args);
536533

compiler/rustc_middle/src/ty/util.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -541,13 +541,15 @@ impl<'tcx> TyCtxt<'tcx> {
541541
Ok(())
542542
}
543543

544-
/// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note
545-
/// that closures have a `DefId`, but the closure *expression* also
546-
/// has a `HirId` that is located within the context where the
547-
/// closure appears (and, sadly, a corresponding `NodeId`, since
548-
/// those are not yet phased out). The parent of the closure's
549-
/// `DefId` will also be the context where it appears.
550-
pub fn is_closure_or_coroutine(self, def_id: DefId) -> bool {
544+
/// Returns `true` if `def_id` refers to a closure, coroutine, or coroutine-closure
545+
/// (i.e. an async closure). These are all represented by `hir::Closure`, and all
546+
/// have the same `DefKind`.
547+
///
548+
/// Note that closures have a `DefId`, but the closure *expression* also has a
549+
// `HirId` that is located within the context where the closure appears (and, sadly,
550+
// a corresponding `NodeId`, since those are not yet phased out). The parent of
551+
// the closure's `DefId` will also be the context where it appears.
552+
pub fn is_closure_like(self, def_id: DefId) -> bool {
551553
matches!(self.def_kind(def_id), DefKind::Closure)
552554
}
553555

compiler/rustc_mir_transform/src/coverage/spans/from_mir.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ fn bcb_to_initial_coverage_spans<'a, 'tcx>(
138138
let (span, visible_macro) =
139139
unexpand_into_body_span_with_visible_macro(expn_span, body_span)?;
140140

141-
Some(SpanFromMir::new(span, visible_macro, bcb, is_closure_or_coroutine(statement)))
141+
Some(SpanFromMir::new(span, visible_macro, bcb, is_closure_like(statement)))
142142
});
143143

144144
let terminator_span = Some(data.terminator()).into_iter().filter_map(move |terminator| {
@@ -153,7 +153,7 @@ fn bcb_to_initial_coverage_spans<'a, 'tcx>(
153153
})
154154
}
155155

156-
fn is_closure_or_coroutine(statement: &Statement<'_>) -> bool {
156+
fn is_closure_like(statement: &Statement<'_>) -> bool {
157157
match statement.kind {
158158
StatementKind::Assign(box (_, Rvalue::Aggregate(box ref agg_kind, _))) => match agg_kind {
159159
AggregateKind::Closure(_, _)

compiler/rustc_monomorphize/src/collector.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1162,7 +1162,7 @@ fn create_fn_mono_item<'tcx>(
11621162
let def_id = instance.def_id();
11631163
if tcx.sess.opts.unstable_opts.profile_closures
11641164
&& def_id.is_local()
1165-
&& tcx.is_closure_or_coroutine(def_id)
1165+
&& tcx.is_closure_like(def_id)
11661166
{
11671167
crate::util::dump_closure_profile(tcx, instance);
11681168
}

compiler/rustc_passes/src/upvars.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use rustc_span::Span;
1111

1212
pub fn provide(providers: &mut Providers) {
1313
providers.upvars_mentioned = |tcx, def_id| {
14-
if !tcx.is_closure_or_coroutine(def_id) {
14+
if !tcx.is_closure_like(def_id) {
1515
return None;
1616
}
1717

src/tools/clippy/clippy_lints/src/redundant_locals.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantLocals {
101101
fn is_by_value_closure_capture(cx: &LateContext<'_>, redefinition: HirId, root_variable: HirId) -> bool {
102102
let closure_def_id = cx.tcx.hir().enclosing_body_owner(redefinition);
103103

104-
cx.tcx.is_closure_or_coroutine(closure_def_id.to_def_id())
104+
cx.tcx.is_closure_like(closure_def_id.to_def_id())
105105
&& cx.tcx.closure_captures(closure_def_id).iter().any(|c| {
106106
matches!(c.info.capture_kind, UpvarCapture::ByValue)
107107
&& matches!(c.place.base, PlaceBase::Upvar(upvar) if upvar.var_path.hir_id == root_variable)
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#![feature(async_closure, noop_waker, async_fn_traits)]
2+
3+
use std::future::Future;
4+
use std::pin::pin;
5+
use std::task::*;
6+
7+
pub fn block_on<T>(fut: impl Future<Output = T>) -> T {
8+
let mut fut = pin!(fut);
9+
let ctx = &mut Context::from_waker(Waker::noop());
10+
11+
loop {
12+
match fut.as_mut().poll(ctx) {
13+
Poll::Pending => {}
14+
Poll::Ready(t) => break t,
15+
}
16+
}
17+
}
18+
19+
async fn call_once(f: impl async FnOnce(DropMe)) {
20+
f(DropMe("world")).await;
21+
}
22+
23+
#[derive(Debug)]
24+
struct DropMe(&'static str);
25+
26+
impl Drop for DropMe {
27+
fn drop(&mut self) {
28+
println!("{}", self.0);
29+
}
30+
}
31+
32+
pub fn main() {
33+
block_on(async {
34+
let b = DropMe("hello");
35+
let async_closure = async move |a: DropMe| {
36+
println!("{a:?} {b:?}");
37+
};
38+
call_once(async_closure).await;
39+
});
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
DropMe("world") DropMe("hello")
2+
world
3+
hello

0 commit comments

Comments
 (0)