Skip to content

Commit 50e0c0d

Browse files
Give better const-checking error for async blocks
1 parent 7820135 commit 50e0c0d

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

compiler/rustc_mir/src/transform/check_consts/ops.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,14 +151,15 @@ impl NonConstOp for FnPtrCast {
151151
}
152152

153153
#[derive(Debug)]
154-
pub struct Generator;
154+
pub struct Generator(pub hir::GeneratorKind);
155155
impl NonConstOp for Generator {
156156
fn status_in_item(&self, _: &ConstCx<'_, '_>) -> Status {
157157
Status::Forbidden
158158
}
159159

160160
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> DiagnosticBuilder<'tcx> {
161-
ccx.tcx.sess.struct_span_err(span, "Generators and `async` functions cannot be `const`")
161+
let msg = format!("{}s are not allowed in {}s", self.0, ccx.const_kind());
162+
ccx.tcx.sess.struct_span_err(span, &msg)
162163
}
163164
}
164165

compiler/rustc_mir/src/transform/check_consts/validation.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -770,6 +770,14 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> {
770770
return;
771771
}
772772

773+
// `async` blocks get lowered to `std::future::from_generator(/* a closure */)`.
774+
let is_async_block = Some(callee) == tcx.lang_items().from_generator_fn();
775+
if is_async_block {
776+
let kind = hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block);
777+
self.check_op(ops::Generator(kind));
778+
return;
779+
}
780+
773781
// HACK: This is to "unstabilize" the `transmute` intrinsic
774782
// within const fns. `transmute` is allowed in all other const contexts.
775783
// This won't really scale to more intrinsics or functions. Let's allow const
@@ -869,7 +877,7 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> {
869877
TerminatorKind::Abort => self.check_op(ops::Abort),
870878

871879
TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
872-
self.check_op(ops::Generator)
880+
self.check_op(ops::Generator(hir::GeneratorKind::Gen))
873881
}
874882

875883
TerminatorKind::Assert { .. }

0 commit comments

Comments
 (0)