diff options
| author | Oli Scherer <git-spam-no-reply9815368754983@oli-obk.de> | 2023-10-19 21:46:28 +0000 |
|---|---|---|
| committer | Oli Scherer <git-spam-no-reply9815368754983@oli-obk.de> | 2023-10-20 21:14:01 +0000 |
| commit | e96ce20b34789d29e925425da6cf138927b80a79 (patch) | |
| tree | 4032e01ddd5137d1ee98b69277953f2962bbf14b /compiler | |
| parent | 60956837cfbf22bd8edd80f57a856e141f7deb8c (diff) | |
| download | rust-e96ce20b34789d29e925425da6cf138927b80a79.tar.gz rust-e96ce20b34789d29e925425da6cf138927b80a79.zip | |
s/generator/coroutine/
Diffstat (limited to 'compiler')
163 files changed, 1081 insertions, 1079 deletions
diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 3722a0774ba..8e7aa59ee34 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1502,7 +1502,7 @@ pub struct LayoutS<FieldIdx: Idx, VariantIdx: Idx> { /// Encodes information about multi-variant layouts. /// Even with `Multiple` variants, a layout still has its own fields! Those are then /// shared between all variants. One of them will be the discriminant, - /// but e.g. generators can have more. + /// but e.g. coroutines can have more. /// /// To access all fields of this layout, both `fields` and the fields of the active variant /// must be taken into account. diff --git a/compiler/rustc_ast_lowering/messages.ftl b/compiler/rustc_ast_lowering/messages.ftl index b9fe99ac72f..91591a71611 100644 --- a/compiler/rustc_ast_lowering/messages.ftl +++ b/compiler/rustc_ast_lowering/messages.ftl @@ -11,8 +11,8 @@ ast_lowering_argument = argument ast_lowering_assoc_ty_parentheses = parenthesized generic arguments cannot be used in associated type constraints -ast_lowering_async_generators_not_supported = - `async` generators are not yet supported +ast_lowering_async_coroutines_not_supported = + `async` coroutines are not yet supported ast_lowering_async_non_move_closure_not_supported = `async` non-`move` closures with parameters are not currently supported @@ -42,6 +42,9 @@ ast_lowering_clobber_abi_not_supported = ast_lowering_closure_cannot_be_static = closures cannot be static +ast_lowering_coroutine_too_many_parameters = + too many parameters for a coroutine (expected 0 or 1 parameters) + ast_lowering_does_not_support_modifiers = the `{$class_name}` register class does not support template modifiers @@ -53,9 +56,6 @@ ast_lowering_functional_record_update_destructuring_assignment = functional record updates are not allowed in destructuring assignments .suggestion = consider removing the trailing pattern -ast_lowering_generator_too_many_parameters = - too many parameters for a generator (expected 0 or 1 parameters) - ast_lowering_generic_type_with_parentheses = parenthesized type parameters may only be used with a `Fn` trait .label = only `Fn` traits may use parentheses diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index 9e8326de5d0..6e1a9eff500 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -131,7 +131,7 @@ pub struct AwaitOnlyInAsyncFnAndBlocks { } #[derive(Diagnostic, Clone, Copy)] -#[diag(ast_lowering_generator_too_many_parameters, code = "E0628")] +#[diag(ast_lowering_coroutine_too_many_parameters, code = "E0628")] pub struct CoroutineTooManyParameters { #[primary_span] pub fn_decl_span: Span, @@ -161,7 +161,7 @@ pub struct FunctionalRecordUpdateDestructuringAssignment { } #[derive(Diagnostic, Clone, Copy)] -#[diag(ast_lowering_async_generators_not_supported, code = "E0727")] +#[diag(ast_lowering_async_coroutines_not_supported, code = "E0727")] pub struct AsyncCoroutinesNotSupported { #[primary_span] pub span: Span, diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index b127eeed1a4..82db30bd05e 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -583,7 +583,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } } - /// Lower an `async` construct to a generator that implements `Future`. + /// Lower an `async` construct to a coroutine that implements `Future`. /// /// This results in: /// @@ -613,7 +613,7 @@ impl<'hir> LoweringContext<'_, 'hir> { span: unstable_span, }; - // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`. + // The closure/coroutine `FnDecl` takes a single (resume) argument of type `input_ty`. let fn_decl = self.arena.alloc(hir::FnDecl { inputs: arena_vec![self; input_ty], output, @@ -637,7 +637,7 @@ impl<'hir> LoweringContext<'_, 'hir> { let params = arena_vec![self; param]; let body = self.lower_body(move |this| { - this.generator_kind = Some(hir::CoroutineKind::Async(async_gen_kind)); + this.coroutine_kind = Some(hir::CoroutineKind::Async(async_gen_kind)); let old_ctx = this.task_context; this.task_context = Some(task_context_hid); @@ -710,7 +710,7 @@ impl<'hir> LoweringContext<'_, 'hir> { /// ``` fn lower_expr_await(&mut self, await_kw_span: Span, expr: &Expr) -> hir::ExprKind<'hir> { let full_span = expr.span.to(await_kw_span); - match self.generator_kind { + match self.coroutine_kind { Some(hir::CoroutineKind::Async(_)) => {} Some(hir::CoroutineKind::Gen) | None => { self.tcx.sess.emit_err(AwaitOnlyInAsyncFnAndBlocks { @@ -887,19 +887,19 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> hir::ExprKind<'hir> { let (binder_clause, generic_params) = self.lower_closure_binder(binder); - let (body_id, generator_option) = self.with_new_scopes(move |this| { + let (body_id, coroutine_option) = self.with_new_scopes(move |this| { let prev = this.current_item; this.current_item = Some(fn_decl_span); - let mut generator_kind = None; + let mut coroutine_kind = None; let body_id = this.lower_fn_body(decl, |this| { let e = this.lower_expr_mut(body); - generator_kind = this.generator_kind; + coroutine_kind = this.coroutine_kind; e }); - let generator_option = - this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability); + let coroutine_option = + this.coroutine_movability_for_fn(&decl, fn_decl_span, coroutine_kind, movability); this.current_item = prev; - (body_id, generator_option) + (body_id, coroutine_option) }); let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params); @@ -915,21 +915,21 @@ impl<'hir> LoweringContext<'_, 'hir> { body: body_id, fn_decl_span: self.lower_span(fn_decl_span), fn_arg_span: Some(self.lower_span(fn_arg_span)), - movability: generator_option, + movability: coroutine_option, constness: self.lower_constness(constness), }); hir::ExprKind::Closure(c) } - fn generator_movability_for_fn( + fn coroutine_movability_for_fn( &mut self, decl: &FnDecl, fn_decl_span: Span, - generator_kind: Option<hir::CoroutineKind>, + coroutine_kind: Option<hir::CoroutineKind>, movability: Movability, ) -> Option<hir::Movability> { - match generator_kind { + match coroutine_kind { Some(hir::CoroutineKind::Gen) => { if decl.inputs.len() > 1 { self.tcx.sess.emit_err(CoroutineTooManyParameters { fn_decl_span }); @@ -1444,12 +1444,12 @@ impl<'hir> LoweringContext<'_, 'hir> { } fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> { - match self.generator_kind { + match self.coroutine_kind { Some(hir::CoroutineKind::Gen) => {} Some(hir::CoroutineKind::Async(_)) => { self.tcx.sess.emit_err(AsyncCoroutinesNotSupported { span }); } - None => self.generator_kind = Some(hir::CoroutineKind::Gen), + None => self.coroutine_kind = Some(hir::CoroutineKind::Gen), } let expr = diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index f363676cbdf..3c165f87dbf 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -82,7 +82,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> { is_in_loop_condition: false, is_in_trait_impl: false, is_in_dyn_type: false, - generator_kind: None, + coroutine_kind: None, task_context: None, current_item: None, impl_trait_defs: Vec::new(), @@ -974,7 +974,7 @@ impl<'hir> LoweringContext<'_, 'hir> { value: hir::Expr<'hir>, ) -> hir::BodyId { let body = hir::Body { - generator_kind: self.generator_kind, + coroutine_kind: self.coroutine_kind, params, value: self.arena.alloc(value), }; @@ -988,12 +988,12 @@ impl<'hir> LoweringContext<'_, 'hir> { &mut self, f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>), ) -> hir::BodyId { - let prev_gen_kind = self.generator_kind.take(); + let prev_gen_kind = self.coroutine_kind.take(); let task_context = self.task_context.take(); let (parameters, result) = f(self); let body_id = self.record_body(parameters, result); self.task_context = task_context; - self.generator_kind = prev_gen_kind; + self.coroutine_kind = prev_gen_kind; body_id } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index c4557e55784..1e51449e70c 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -111,10 +111,10 @@ struct LoweringContext<'a, 'hir> { /// Collect items that were created by lowering the current owner. children: Vec<(LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>)>, - generator_kind: Option<hir::CoroutineKind>, + coroutine_kind: Option<hir::CoroutineKind>, /// When inside an `async` context, this is the `HirId` of the - /// `task_context` local bound to the resume argument of the generator. + /// `task_context` local bound to the resume argument of the coroutine. task_context: Option<hir::HirId>, /// Used to get the current `fn`'s def span to point to when using `await` diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 9328b83e8f3..34532967d9e 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -554,7 +554,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) { "consider removing `for<...>`" ); gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental"); - gate_all!(generators, "yield syntax is experimental"); + gate_all!(coroutines, "yield syntax is experimental"); gate_all!(raw_ref_op, "raw address of syntax is experimental"); gate_all!(const_trait_impl, "const trait impls are experimental"); gate_all!( diff --git a/compiler/rustc_borrowck/messages.ftl b/compiler/rustc_borrowck/messages.ftl index 2c7b97afa80..8c5a1d89709 100644 --- a/compiler/rustc_borrowck/messages.ftl +++ b/compiler/rustc_borrowck/messages.ftl @@ -1,20 +1,20 @@ borrowck_assign_due_to_use_closure = assignment occurs due to use in closure -borrowck_assign_due_to_use_generator = - assign occurs due to use in generator +borrowck_assign_due_to_use_coroutine = + assign occurs due to use in coroutine borrowck_assign_part_due_to_use_closure = assignment to part occurs due to use in closure -borrowck_assign_part_due_to_use_generator = - assign to part occurs due to use in generator +borrowck_assign_part_due_to_use_coroutine = + assign to part occurs due to use in coroutine borrowck_borrow_due_to_use_closure = borrow occurs due to use in closure -borrowck_borrow_due_to_use_generator = - borrow occurs due to use in generator +borrowck_borrow_due_to_use_coroutine = + borrow occurs due to use in coroutine borrowck_calling_operator_moves_lhs = calling this operator moves the left-hand side @@ -142,11 +142,11 @@ borrowck_partial_var_move_by_use_in_closure = *[false] moved } due to use in closure -borrowck_partial_var_move_by_use_in_generator = +borrowck_partial_var_move_by_use_in_coroutine = variable {$is_partial -> [true] partially moved *[false] moved - } due to use in generator + } due to use in coroutine borrowck_returned_async_block_escaped = returns an `async` block that contains a reference to a captured variable, which then escapes the closure body @@ -180,15 +180,15 @@ borrowck_ty_no_impl_copy = borrowck_use_due_to_use_closure = use occurs due to use in closure -borrowck_use_due_to_use_generator = - use occurs due to use in generator +borrowck_use_due_to_use_coroutine = + use occurs due to use in coroutine borrowck_used_impl_require_static = the used `impl` has a `'static` requirement borrowck_value_capture_here = value captured {$is_within -> - [true] here by generator + [true] here by coroutine *[false] here } @@ -207,8 +207,8 @@ borrowck_value_moved_here = borrowck_var_borrow_by_use_in_closure = borrow occurs due to use in closure -borrowck_var_borrow_by_use_in_generator = - borrow occurs due to use in generator +borrowck_var_borrow_by_use_in_coroutine = + borrow occurs due to use in coroutine borrowck_var_borrow_by_use_place_in_closure = {$is_single_var -> @@ -216,11 +216,11 @@ borrowck_var_borrow_by_use_place_in_closure = [false] borrows occur } due to use of {$place} in closure -borrowck_var_borrow_by_use_place_in_generator = +borrowck_var_borrow_by_use_place_in_coroutine = {$is_single_var -> *[true] borrow occurs [false] borrows occur - } due to use of {$place} in generator + } due to use of {$place} in coroutine borrowck_var_cannot_escape_closure = captured variable cannot escape `FnMut` closure body @@ -234,8 +234,8 @@ borrowck_var_does_not_need_mut = borrowck_var_first_borrow_by_use_place_in_closure = first borrow occurs due to use of {$place} in closure -borrowck_var_first_borrow_by_use_place_in_generator = - first borrow occurs due to use of {$place} in generator +borrowck_var_first_borrow_by_use_place_in_coroutine = + first borrow occurs due to use of {$place} in coroutine borrowck_var_here_captured = variable captured here @@ -244,8 +244,8 @@ borrowck_var_here_defined = variable defined here borrowck_var_move_by_use_in_closure = move occurs due to use in closure -borrowck_var_move_by_use_in_generator = - move occurs due to use in generator +borrowck_var_move_by_use_in_coroutine = + move occurs due to use in coroutine borrowck_var_mutable_borrow_by_use_place_in_closure = mutable borrow occurs due to use of {$place} in closure @@ -253,5 +253,5 @@ borrowck_var_mutable_borrow_by_use_place_in_closure = borrowck_var_second_borrow_by_use_place_in_closure = second borrow occurs due to use of {$place} in closure -borrowck_var_second_borrow_by_use_place_in_generator = - second borrow occurs due to use of {$place} in generator +borrowck_var_second_borrow_by_use_place_in_coroutine = + second borrow occurs due to use of {$place} in coroutine diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs index a2c7e767b4c..2ceec1b5658 100644 --- a/compiler/rustc_borrowck/src/borrowck_errors.rs +++ b/compiler/rustc_borrowck/src/borrowck_errors.rs @@ -368,7 +368,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { err } - pub(crate) fn cannot_borrow_across_generator_yield( + pub(crate) fn cannot_borrow_across_coroutine_yield( &self, span: Span, yield_span: Span, @@ -377,7 +377,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { self, span, E0626, - "borrow may still be in use when generator yields", + "borrow may still be in use when coroutine yields", ); err.span_label(yield_span, "possible yield occurs here"); err diff --git a/compiler/rustc_borrowck/src/def_use.rs b/compiler/rustc_borrowck/src/def_use.rs index b719a610e07..201f0df1238 100644 --- a/compiler/rustc_borrowck/src/def_use.rs +++ b/compiler/rustc_borrowck/src/def_use.rs @@ -44,7 +44,7 @@ pub fn categorize(context: PlaceContext) -> Option<DefUse> { PlaceContext::MutatingUse(MutatingUseContext::Projection) | // Borrows only consider their local used at the point of the borrow. - // This won't affect the results since we use this analysis for generators + // This won't affect the results since we use this analysis for coroutines // and we only care about the result at suspension points. Borrows cannot // cross suspension points so this behavior is unproblematic. PlaceContext::MutatingUse(MutatingUseContext::Borrow) | diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index d9f87f80aea..3b640cafb7a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -926,8 +926,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let borrow_spans = self.borrow_spans(span, location); let span = borrow_spans.args_or_use(); - let container_name = if issued_spans.for_generator() || borrow_spans.for_generator() { - "generator" + let container_name = if issued_spans.for_coroutine() || borrow_spans.for_coroutine() { + "coroutine" } else { "closure" }; @@ -1575,7 +1575,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // Get closure's arguments let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else { - /* hir::Closure can be a generator too */ + /* hir::Closure can be a coroutine too */ return; }; let sig = args.as_closure().sig(); @@ -1949,7 +1949,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ( Some(name), BorrowExplanation::UsedLater(LaterUseKind::ClosureCapture, var_or_use_span, _), - ) if borrow_spans.for_generator() || borrow_spans.for_closure() => self + ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self .report_escaping_closure_capture( borrow_spans, borrow_span, @@ -1974,7 +1974,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { span, .. }, - ) if borrow_spans.for_generator() || borrow_spans.for_closure() => self + ) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self .report_escaping_closure_capture( borrow_spans, borrow_span, @@ -2077,8 +2077,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { .unwrap_or_else(|| { match &self.infcx.tcx.def_kind(self.mir_def_id()) { DefKind::Closure => "enclosing closure", - DefKind::Coroutine => "enclosing generator", - kind => bug!("expected closure or generator, found {:?}", kind), + DefKind::Coroutine => "enclosing coroutine", + kind => bug!("expected closure or coroutine, found {:?}", kind), } .to_string() }) @@ -2112,7 +2112,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { borrow_spans.args_subdiag(&mut err, |args_span| { crate::session_diagnostics::CaptureArgLabel::Capture { - is_within: borrow_spans.for_generator(), + is_within: borrow_spans.for_coroutine(), args_span, } }); @@ -2353,7 +2353,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { borrow_spans.args_subdiag(&mut err, |args_span| { crate::session_diagnostics::CaptureArgLabel::Capture { - is_within: borrow_spans.for_generator(), + is_within: borrow_spans.for_coroutine(), args_span, } }); @@ -2481,14 +2481,14 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } Err(_) => (args_span, "move |<args>| <body>"), }; - let kind = match use_span.generator_kind() { - Some(generator_kind) => match generator_kind { + let kind = match use_span.coroutine_kind() { + Some(coroutine_kind) => match coroutine_kind { CoroutineKind::Async(async_kind) => match async_kind { AsyncCoroutineKind::Block => "async block", AsyncCoroutineKind::Closure => "async closure", _ => bug!("async block/closure expected, but async function found."), }, - CoroutineKind::Gen => "generator", + CoroutineKind::Gen => "coroutine", }, None => "closure", }; @@ -2517,7 +2517,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } ConstraintCategory::CallArgument(_) => { fr_name.highlight_region_name(&mut err); - if matches!(use_span.generator_kind(), Some(CoroutineKind::Async(_))) { + if matches!(use_span.coroutine_kind(), Some(CoroutineKind::Async(_))) { err.note( "async blocks are not executed immediately and must either take a \ reference or ownership of outside variables they use", diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index f1b9f5f823d..8a930ca59a3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -182,7 +182,7 @@ impl<'tcx> BorrowExplanation<'tcx> { // Otherwise, just report the whole type (and use // the intentionally fuzzy phrase "destructor") ty::Closure(..) => ("destructor", "closure".to_owned()), - ty::Coroutine(..) => ("destructor", "generator".to_owned()), + ty::Coroutine(..) => ("destructor", "coroutine".to_owned()), _ => ("destructor", format!("type `{}`", local_decl.ty)), }; diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 8104e05e754..47a387e25e3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -501,8 +501,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { pub(super) enum UseSpans<'tcx> { /// The access is caused by capturing a variable for a closure. ClosureUse { - /// This is true if the captured variable was from a generator. - generator_kind: Option<CoroutineKind>, + /// This is true if the captured variable was from a coroutine. + coroutine_kind: Option<CoroutineKind>, /// The span of the args of the closure, including the `move` keyword if /// it's present. args_span: Span, @@ -569,9 +569,9 @@ impl UseSpans<'_> { } } - pub(super) fn generator_kind(self) -> Option<CoroutineKind> { + pub(super) fn coroutine_kind(self) -> Option<CoroutineKind> { match self { - UseSpans::ClosureUse { generator_kind, .. } => generator_kind, + UseSpans::ClosureUse { coroutine_kind, .. } => coroutine_kind, _ => None, } } @@ -596,8 +596,8 @@ impl UseSpans<'_> { ) { use crate::InitializationRequiringAction::*; use CaptureVarPathUseCause::*; - if let UseSpans::ClosureUse { generator_kind, path_span, .. } = self { - match generator_kind { + if let UseSpans::ClosureUse { coroutine_kind, path_span, .. } = self { + match coroutine_kind { Some(_) => { err.subdiagnostic(match action { Borrow => BorrowInCoroutine { path_span }, @@ -626,7 +626,7 @@ impl UseSpans<'_> { kind: Option<rustc_middle::mir::BorrowKind>, f: impl FnOnce(Option<CoroutineKind>, Span) -> CaptureVarCause, ) { - if let UseSpans::ClosureUse { generator_kind, capture_kind_span, path_span, .. } = self { + if let UseSpans::ClosureUse { coroutine_kind, capture_kind_span, path_span, .. } = self { if capture_kind_span != path_span { err.subdiagnostic(match kind { Some(kd) => match kd { @@ -642,7 +642,7 @@ impl UseSpans<'_> { None => CaptureVarKind::Move { kind_span: capture_kind_span }, }); }; - let diag = f(generator_kind, path_span); + let diag = f(coroutine_kind, path_span); match handler { Some(hd) => err.eager_subdiagnostic(hd, diag), None => err.subdiagnostic(diag), @@ -653,15 +653,15 @@ impl UseSpans<'_> { /// Returns `false` if this place is not used in a closure. pub(super) fn for_closure(&self) -> bool { match *self { - UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_none(), + UseSpans::ClosureUse { coroutine_kind, .. } => coroutine_kind.is_none(), _ => false, } } - /// Returns `false` if this place is not used in a generator. - pub(super) fn for_generator(&self) -> bool { + /// Returns `false` if this place is not used in a coroutine. + pub(super) fn for_coroutine(&self) -> bool { match *self { - UseSpans::ClosureUse { generator_kind, .. } => generator_kind.is_some(), + UseSpans::ClosureUse { coroutine_kind, .. } => coroutine_kind.is_some(), _ => false, } } @@ -785,10 +785,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { { debug!("move_spans: def_id={:?} places={:?}", def_id, places); let def_id = def_id.expect_local(); - if let Some((args_span, generator_kind, capture_kind_span, path_span)) = + if let Some((args_span, coroutine_kind, capture_kind_span, path_span)) = self.closure_span(def_id, moved_place, places) { - return ClosureUse { generator_kind, args_span, capture_kind_span, path_span }; + return ClosureUse { coroutine_kind, args_span, capture_kind_span, path_span }; } } @@ -800,11 +800,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { | FakeReadCause::ForLet(Some(closure_def_id)) => { debug!("move_spans: def_id={:?} place={:?}", closure_def_id, place); let places = &[Operand::Move(place)]; - if let Some((args_span, generator_kind, capture_kind_span, path_span)) = + if let Some((args_span, coroutine_kind, capture_kind_span, path_span)) = self.closure_span(closure_def_id, moved_place, IndexSlice::from_raw(places)) { return ClosureUse { - generator_kind, + coroutine_kind, args_span, capture_kind_span, path_span, @@ -914,7 +914,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { for stmt in statements.chain(maybe_additional_statement) { if let StatementKind::Assign(box (_, Rvalue::Aggregate(kind, places))) = &stmt.kind { - let (&def_id, is_generator) = match kind { + let (&def_id, is_coroutine) = match kind { box AggregateKind::Closure(def_id, _) => (def_id, false), box AggregateKind::Coroutine(def_id, _, _) => (def_id, true), _ => continue, @@ -922,13 +922,13 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let def_id = def_id.expect_local(); debug!( - "borrow_spans: def_id={:?} is_generator={:?} places={:?}", - def_id, is_generator, places + "borrow_spans: def_id={:?} is_coroutine={:?} places={:?}", + def_id, is_coroutine, places ); - if let Some((args_span, generator_kind, capture_kind_span, path_span)) = + if let Some((args_span, coroutine_kind, capture_kind_span, path_span)) = self.closure_span(def_id, Place::from(target).as_ref(), places) { - return ClosureUse { generator_kind, args_span, capture_kind_span, path_span }; + return ClosureUse { coroutine_kind, args_span, capture_kind_span, path_span }; } else { return OtherUse(use_span); } @@ -942,7 +942,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { OtherUse(use_span) } - /// Finds the spans of a captured place within a closure or generator. + /// Finds the spans of a captured place within a closure or coroutine. /// The first span is the location of the use resulting in the capture kind of the capture /// The second span is the location the use resulting in the captured path of the capture fn closure_span( @@ -968,11 +968,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { { debug!("closure_span: found captured local {:?}", place); let body = self.infcx.tcx.hir().body(body); - let generator_kind = body.generator_kind(); + let coroutine_kind = body.coroutine_kind(); return Some(( fn_decl_span, - generator_kind, + coroutine_kind, captured_place.get_capture_kind_span(self.infcx.tcx), captured_place.get_path_span(self.infcx.tcx), )); diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index e5ffc8a1114..003254b8da1 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -62,7 +62,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { local, projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)], } => { - debug_assert!(is_closure_or_generator( + debug_assert!(is_closure_or_coroutine( Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty )); @@ -122,7 +122,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { { item_msg = access_place_desc; debug_assert!(self.body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty.is_ref()); - debug_assert!(is_closure_or_generator( + debug_assert!(is_closure_or_coroutine( the_place_err.ty(self.body, self.infcx.tcx).ty )); @@ -385,7 +385,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { local, projection: [proj_base @ .., ProjectionElem::Field(upvar_index, _)], } => { - debug_assert!(is_closure_or_generator( + debug_assert!(is_closure_or_coroutine( Place::ty_from(local, proj_base, self.body, self.infcx.tcx).ty )); @@ -1377,8 +1377,8 @@ fn suggest_ampmut<'tcx>( } } -fn is_closure_or_generator(ty: Ty<'_>) -> bool { - ty.is_closure() || ty.is_generator() +fn is_closure_or_coroutine(ty: Ty<'_>) -> bool { + ty.is_closure() || ty.is_coroutine() } /// Given a field that needs to be mutable, returns a span where the " mut " could go. diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index d8b89e64606..a0a809123c0 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -580,7 +580,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let err = FnMutError { span: *span, ty_err: match output_ty.kind() { - ty::Coroutine(def, ..) if self.infcx.tcx.generator_is_async(*def) => { + ty::Coroutine(def, ..) if self.infcx.tcx.coroutine_is_async(*def) => { FnMutReturnTypeErr::ReturnAsyncBlock { span: *span } } _ if output_ty.contains_closure() => { @@ -1036,7 +1036,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { .. }) => { let body = map.body(*body); - if !matches!(body.generator_kind, Some(hir::CoroutineKind::Async(..))) { + if !matches!(body.coroutine_kind, Some(hir::CoroutineKind::Async(..))) { closure_span = Some(expr.span.shrink_to_lo()); } } diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 7756dbf53a7..b35662a1332 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -41,7 +41,7 @@ pub(crate) enum RegionNameSource { AnonRegionFromUpvar(Span, Symbol), /// The region corresponding to the return type of a closure. AnonRegionFromOutput(RegionNameHighlight, &'static str), - /// The region from a type yielded by a generator. + /// The region from a type yielded by a coroutine. AnonRegionFromYieldTy(Span, String), /// An anonymous region from an async fn. AnonRegionFromAsyncFn(Span), @@ -322,7 +322,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { let def_ty = self.regioncx.universal_regions().defining_ty; let DefiningTy::Closure(_, args) = def_ty else { - // Can't have BrEnv in functions, constants or generators. + // Can't have BrEnv in functions, constants or coroutines. bug!("BrEnv outside of closure."); }; let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) = @@ -680,7 +680,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { } hir::FnRetTy::Return(hir_ty) => (fn_decl.output.span(), Some(hir_ty)), }; - let mir_description = match hir.body(body).generator_kind { + let mir_description = match hir.body(body).coroutine_kind { Some(hir::CoroutineKind::Async(gen)) => match gen { hir::AsyncCoroutineKind::Block => " of async block", hir::AsyncCoroutineKind::Closure => " of async closure", @@ -689,7 +689,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { hir.get_by_def_id(hir.get_parent_item(mir_hir_id).def_id); let output = &parent_item .fn_decl() - .expect("generator lowered from async fn should be in fn") + .expect("coroutine lowered from async fn should be in fn") .output; span = output.span(); if let hir::FnRetTy::Return(ret) = output { @@ -698,7 +698,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { " of async function" } }, - Some(hir::CoroutineKind::Gen) => " of generator", + Some(hir::CoroutineKind::Gen) => " of coroutine", None => " of closure", }; (span, mir_description, hir_ty) @@ -793,7 +793,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { &self, fr: RegionVid, ) -> Option<RegionName> { - // Note: generators from `async fn` yield `()`, so we don't have to + // Note: coroutines from `async fn` yield `()`, so we don't have to // worry about them here. let yield_ty = self.regioncx.universal_regions().yield_ty?; debug!("give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}", yield_ty); diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 26abd2542c8..ee34be847cc 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -302,8 +302,8 @@ fn do_mir_borrowck<'tcx>( .pass_name("borrowck") .iterate_to_fixpoint(); - let movable_generator = - // The first argument is the generator type passed by value + let movable_coroutine = + // The first argument is the coroutine type passed by value if let Some(local) = body.local_decls.raw.get(1) // Get the interior types and args which typeck computed && let ty::Coroutine(_, _, hir::Movability::Static) = local.ty.kind() @@ -323,7 +323,7 @@ fn do_mir_borrowck<'tcx>( body: promoted_body, move_data: &move_data, location_table, // no need to create a real one for the promoted, it is not used - movable_generator, + movable_coroutine, fn_self_span_reported: Default::default(), locals_are_invalidated_at_exit, access_place_error_reported: Default::default(), @@ -351,7 +351,7 @@ fn do_mir_borrowck<'tcx>( body, move_data: &mdpe.move_data, location_table, - movable_generator, + movable_coroutine, locals_are_invalidated_at_exit, fn_self_span_reported: Default::default(), access_place_error_reported: Default::default(), @@ -536,7 +536,7 @@ struct MirBorrowckCtxt<'cx, 'tcx> { /// when MIR borrowck begins. location_table: &'cx LocationTable, - movable_generator: bool, + movable_coroutine: bool, /// This keeps track of whether local variables are free-ed when the function /// exits even without a `StorageDead`, which appears to be the case for /// constants. @@ -797,7 +797,7 @@ impl<'cx, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx, R> for MirBorro match term.kind { TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => { - if self.movable_generator { + if self.movable_coroutine { // Look for any active borrows to locals let borrow_set = self.borrow_set.clone(); for i in flow_state.borrows.iter() { @@ -1549,12 +1549,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } /// Reports an error if this is a borrow of local data. - /// This is called for all Yield expressions on movable generators + /// This is called for all Yield expressions on movable coroutines fn check_for_local_borrow(&mut self, borrow: &BorrowData<'tcx>, yield_span: Span) { debug!("check_for_local_borrow({:?})", borrow); if borrow_of_local_data(borrow.borrowed_place) { - let err = self.cannot_borrow_across_generator_yield( + let err = self.cannot_borrow_across_coroutine_yield( self.retrieve_borrow_spans(borrow).var_or_use(), yield_span, ); diff --git a/compiler/rustc_borrowck/src/path_utils.rs b/compiler/rustc_borrowck/src/path_utils.rs index ed93a560981..51e318f0854 100644 --- a/compiler/rustc_borrowck/src/path_utils.rs +++ b/compiler/rustc_borrowck/src/path_utils.rs @@ -137,7 +137,7 @@ pub(super) fn is_active<'tcx>( } /// Determines if a given borrow is borrowing local data -/// This is called for all Yield expressions on movable generators +/// This is called for all Yield expressions on movable coroutines pub(super) fn borrow_of_local_data(place: Place<'_>) -> bool { // Reborrow of already borrowed data is ignored // Any errors will be caught on the initial borrow @@ -165,7 +165,7 @@ pub(crate) fn is_upvar_field_projection<'tcx>( match place_ref.last_projection() { Some((place_base, ProjectionElem::Field(field, _ty))) => { let base_ty = place_base.ty(body, tcx).ty; - if (base_ty.is_closure() || base_ty.is_generator()) + if (base_ty.is_closure() || base_ty.is_coroutine()) && (!by_ref || upvars[field.index()].by_ref) { Some(field) diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index 31502b336d4..e321b92603d 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -139,22 +139,22 @@ pub(crate) enum RequireStaticErr { #[derive(Subdiagnostic)] pub(crate) enum CaptureVarPathUseCause { - #[label(borrowck_borrow_due_to_use_generator)] + #[label(borrowck_borrow_due_to_use_coroutine)] BorrowInCoroutine { #[primary_span] path_span: Span, }, - #[label(borrowck_use_due_to_use_generator)] + #[label(borrowck_use_due_to_use_coroutine)] UseInCoroutine { #[primary_span] path_span: Span, }, - #[label(borrowck_assign_due_to_use_generator)] + #[label(borrowck_assign_due_to_use_coroutine)] AssignInCoroutine { #[primary_span] path_span: Span, }, - #[label(borrowck_assign_part_due_to_use_generator)] + #[label(borrowck_assign_part_due_to_use_coroutine)] AssignPartInCoroutine { #[primary_span] path_span: Span, @@ -202,7 +202,7 @@ pub(crate) enum CaptureVarKind { #[derive(Subdiagnostic)] pub(crate) enum CaptureVarCause { - #[label(borrowck_var_borrow_by_use_place_in_generator)] + #[label(borrowck_var_borrow_by_use_place_in_coroutine)] BorrowUsePlaceCoroutine { is_single_var: bool, place: String, @@ -216,7 +216,7 @@ pub(crate) enum CaptureVarCause { #[primary_span] var_span: Span, }, - #[label(borrowck_var_borrow_by_use_in_generator)] + #[label(borrowck_var_borrow_by_use_in_coroutine)] BorrowUseInCoroutine { #[primary_span] var_span: Span, @@ -226,7 +226,7 @@ pub(crate) enum CaptureVarCause { #[primary_span] var_span: Span, }, - #[label(borrowck_var_move_by_use_in_generator)] + #[label(borrowck_var_move_by_use_in_coroutine)] MoveUseInCoroutine { #[primary_span] var_span: Span, @@ -236,7 +236,7 @@ pub(crate) enum CaptureVarCause { #[primary_span] var_span: Span, }, - #[label(borrowck_var_first_borrow_by_use_place_in_generator)] + #[label(borrowck_var_first_borrow_by_use_place_in_coroutine)] FirstBorrowUsePlaceCoroutine { place: String, #[primary_span] @@ -248,7 +248,7 @@ pub(crate) enum CaptureVarCause { #[primary_span] var_span: Span, }, - #[label(borrowck_var_second_borrow_by_use_place_in_generator)] + #[label(borrowck_var_second_borrow_by_use_place_in_coroutine)] SecondBorrowUsePlaceCoroutine { place: String, #[primary_span] @@ -266,7 +266,7 @@ pub(crate) enum CaptureVarCause { #[primary_span] var_span: Span, }, - #[label(borrowck_partial_var_move_by_use_in_generator)] + #[label(borrowck_partial_var_move_by_use_in_coroutine)] PartialMoveUseInCoroutine { #[primary_span] var_span: Span, diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index eec886b7be4..d053d0a4b3b 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -101,7 +101,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { ); // We will not have a universal_regions.yield_ty if we yield (by accident) - // outside of a generator and return an `impl Trait`, so emit a delay_span_bug + // outside of a coroutine and return an `impl Trait`, so emit a delay_span_bug // because we don't want to panic in an assert here if we've already got errors. if body.yield_ty().is_some() != universal_regions.yield_ty.is_some() { self.tcx().sess.delay_span_bug( diff --git a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs index 21da05c32dd..80e6c6c1dfb 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs @@ -101,7 +101,7 @@ pub(super) fn trace<'mir, 'tcx>( results.dropck_boring_locals(boring_locals); } -/// Contextual state for the type-liveness generator. +/// Contextual state for the type-liveness coroutine. struct LivenessContext<'me, 'typeck, 'flow, 'tcx> { /// Current type-checker, giving us our inference context etc. typeck: &'me mut TypeChecker<'typeck, 'tcx>, diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index c8b58dafc7f..9eb02be2f15 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -671,8 +671,8 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { PlaceTy { ty: base_ty, variant_index: Some(index) } } } - // We do not need to handle generators here, because this runs - // before the generator transform stage. + // We do not need to handle coroutines here, because this runs + // before the coroutine transform stage. _ => { let ty = if let Some(name) = maybe_name { span_mirbug_and_err!( @@ -775,12 +775,12 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() { ty::Adt(adt_def, args) => (adt_def.variant(variant_index), args), ty::Coroutine(def_id, args, _) => { - let mut variants = args.as_generator().state_tys(def_id, tcx); + let mut variants = args.as_coroutine().state_tys(def_id, tcx); let Some(mut variant) = variants.nth(variant_index.into()) else { bug!( - "variant_index of generator out of range: {:?}/{:?}", + "variant_index of coroutine out of range: {:?}/{:?}", variant_index, - args.as_generator().state_tys(def_id, tcx).count() + args.as_coroutine().state_tys(def_id, tcx).count() ); }; return match variant.nth(field.index()) { @@ -788,7 +788,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }), }; } - _ => bug!("can't have downcast of non-adt non-generator type"), + _ => bug!("can't have downcast of non-adt non-coroutine type"), }, PlaceTy { ty, variant_index: None } => match *ty.kind() { ty::Adt(adt_def, args) if !adt_def.is_enum() => { @@ -805,10 +805,10 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { ty::Coroutine(_, args, _) => { // Only prefix fields (upvars and current state) are // accessible without a variant index. - return match args.as_generator().prefix_tys().get(field.index()) { + return match args.as_coroutine().prefix_tys().get(field.index()) { Some(ty) => Ok(*ty), None => Err(FieldAccessError::OutOfRange { - field_count: args.as_generator().prefix_tys().len(), + field_count: args.as_coroutine().prefix_tys().len(), }), }; } @@ -1468,7 +1468,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let value_ty = value.ty(body, tcx); match body.yield_ty() { - None => span_mirbug!(self, term, "yield in non-generator"), + None => span_mirbug!(self, term, "yield in non-coroutine"), Some(ty) => { if let Err(terr) = self.sub_types( value_ty, @@ -1650,7 +1650,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } TerminatorKind::CoroutineDrop { .. } => { if is_cleanup { - span_mirbug!(self, block_data, "generator_drop in cleanup block") + span_mirbug!(self, block_data, "coroutine_drop in cleanup block") } } TerminatorKind::Yield { resume, drop, .. } => { @@ -1801,10 +1801,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // It doesn't make sense to look at a field beyond the prefix; // these require a variant index, and are not initialized in // aggregate rvalues. - match args.as_generator().prefix_tys().get(field_index.as_usize()) { + match args.as_coroutine().prefix_tys().get(field_index.as_usize()) { Some(ty) => Ok(*ty), None => Err(FieldAccessError::OutOfRange { - field_count: args.as_generator().prefix_tys().len(), + field_count: args.as_coroutine().prefix_tys().len(), }), } } @@ -2673,7 +2673,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let parent_args = match tcx.def_kind(def_id) { DefKind::Closure => args.as_closure().parent_args(), - DefKind::Coroutine => args.as_generator().parent_args(), + DefKind::Coroutine => args.as_coroutine().parent_args(), DefKind::InlineConst => args.as_inline_const().parent_args(), other => bug!("unexpected item {:?}", other), }; diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index ef793757162..7897a5a63ba 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -58,7 +58,7 @@ pub struct UniversalRegions<'tcx> { num_universals: usize, /// The "defining" type for this function, with all universal - /// regions instantiated. For a closure or generator, this is the + /// regions instantiated. For a closure or coroutine, this is the /// closure type, but for a top-level function it's the `FnDef`. pub defining_ty: DefiningTy<'tcx>, @@ -91,9 +91,9 @@ pub enum DefiningTy<'tcx> { /// `ClosureArgs::closure_sig_ty`. Closure(DefId, GenericArgsRef<'tcx>), - /// The MIR is a generator. The signature is that generators take + /// The MIR is a coroutine. The signature is that coroutines take /// no parameters and return the result of - /// `ClosureArgs::generator_return_ty`. + /// `ClosureArgs::coroutine_return_ty`. Coroutine(DefId, GenericArgsRef<'tcx>, hir::Movability), /// The MIR is a fn item with the given `DefId` and args. The signature @@ -112,13 +112,13 @@ pub enum DefiningTy<'tcx> { impl<'tcx> DefiningTy<'tcx> { /// Returns a list of all the upvar types for this MIR. If this is - /// not a closure or generator, there are no upvars, and hence it + /// not a closure or coroutine, there are no upvars, and hence it /// will be an empty list. The order of types in this list will /// match up with the upvar order in the HIR, typesystem, and MIR. pub fn upvar_tys(self) -> &'tcx ty::List<Ty<'tcx>> { match self { DefiningTy::Closure(_, args) => args.as_closure().upvar_tys(), - DefiningTy::Coroutine(_, args, _) => args.as_generator().upvar_tys(), + DefiningTy::Coroutine(_, args, _) => args.as_coroutine().upvar_tys(), DefiningTy::FnDef(..) | DefiningTy::Const(..) | DefiningTy::InlineConst(..) => { ty::List::empty() } @@ -178,7 +178,7 @@ pub enum RegionClassification { Global, /// An **external** region is only relevant for - /// closures, generators, and inline consts. In that + /// closures, coroutines, and inline consts. In that /// case, it refers to regions that are free in the type /// -- basically, something bound in the surrounding context. /// @@ -196,7 +196,7 @@ pub enum RegionClassification { /// Here, the lifetimes `'a` and `'b` would be **external** to the /// closure. /// - /// If we are not analyzing a closure/generator/inline-const, + /// If we are not analyzing a closure/coroutine/inline-const, /// there are no external lifetimes. External, @@ -362,7 +362,7 @@ impl<'tcx> UniversalRegions<'tcx> { .collect::<Vec<_>>() ); err.note(format!( - "defining type: {} with generator args [\n {},\n]", + "defining type: {} with coroutine args [\n {},\n]", tcx.def_path_str_with_args(def_id, args), v.join(",\n "), )); @@ -426,13 +426,13 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { let typeck_root_def_id = self.infcx.tcx.typeck_root_def_id(self.mir_def.to_def_id()); - // If this is a 'root' body (not a closure/generator/inline const), then + // If this is a 'root' body (not a closure/coroutine/inline const), then // there are no extern regions, so the local regions start at the same // position as the (empty) sub-list of extern regions let first_local_index = if self.mir_def.to_def_id() == typeck_root_def_id { first_extern_index } else { - // If this is a closure, generator, or inline-const, then the late-bound regions from the enclosing + // If this is a closure, coroutine, or inline-const, then the late-bound regions from the enclosing // function/closures are actually external regions to us. For example, here, 'a is not local // to the closure c (although it is local to the fn foo): // fn foo<'a>() { @@ -528,7 +528,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { debug!("build: local regions = {}..{}", first_local_index, num_universals); let yield_ty = match defining_ty { - DefiningTy::Coroutine(_, args, _) => Some(args.as_generator().yield_ty()), + DefiningTy::Coroutine(_, args, _) => Some(args.as_coroutine().yield_ty()), _ => None, }; @@ -688,11 +688,11 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { DefiningTy::Coroutine(def_id, args, movability) => { assert_eq!(self.mir_def.to_def_id(), def_id); - let resume_ty = args.as_generator().resume_ty(); - let output = args.as_generator().return_ty(); - let generator_ty = Ty::new_generator(tcx, def_id, args, movability); + let resume_ty = args.as_coroutine().resume_ty(); + let output = args.as_coroutine().return_ty(); + let coroutine_ty = Ty::new_coroutine(tcx, def_id, args, movability); let inputs_and_output = - self.infcx.tcx.mk_type_list(&[generator_ty, resume_ty, output]); + self.infcx.tcx.mk_type_list(&[coroutine_ty, resume_ty, output]); ty::Binder::dummy(inputs_and_output) } diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index 9c57f68f0b8..c7999a226c7 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -179,7 +179,7 @@ fn entry_point_type(item: &ast::Item, at_root: bool) -> EntryPointType { } /// A folder used to remove any entry points (like fn main) because the harness -/// generator will provide its own +/// coroutine will provide its own struct EntryPointCleaner<'a> { // Current depth in the ast sess: &'a Session, diff --git a/compiler/rustc_codegen_cranelift/example/std_example.rs b/compiler/rustc_codegen_cranelift/example/std_example.rs index edebc3d4c4d..9bd2ab5c638 100644 --- a/compiler/rustc_codegen_cranelift/example/std_example.rs +++ b/compiler/rustc_codegen_cranelift/example/std_example.rs @@ -1,7 +1,7 @@ #![feature( core_intrinsics, - generators, - generator_trait, + coroutines, + coroutine_trait, is_sorted, repr_simd, tuple_trait, diff --git a/compiler/rustc_codegen_gcc/example/std_example.rs b/compiler/rustc_codegen_gcc/example/std_example.rs index 5bcc2c3315c..dc0aad04a78 100644 --- a/compiler/rustc_codegen_gcc/example/std_example.rs +++ b/compiler/rustc_codegen_gcc/example/std_example.rs @@ -1,4 +1,4 @@ -#![feature(core_intrinsics, generators, generator_trait, is_sorted)] +#![feature(core_intrinsics, coroutines, coroutine_trait, is_sorted)] #[cfg(feature="master")] use std::arch::x86_64::*; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 9186f685ff0..865bf01c8c1 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -460,7 +460,7 @@ pub fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll D } ty::FnDef(..) | ty::FnPtr(_) => build_subroutine_type_di_node(cx, unique_type_id), ty::Closure(..) => build_closure_env_di_node(cx, unique_type_id), - ty::Coroutine(..) => enums::build_generator_di_node(cx, unique_type_id), + ty::Coroutine(..) => enums::build_coroutine_di_node(cx, unique_type_id), ty::Adt(def, ..) => match def.adt_kind() { AdtKind::Struct => build_struct_type_di_node(cx, unique_type_id), AdtKind::Union => build_union_type_di_node(cx, unique_type_id), @@ -1026,20 +1026,20 @@ fn build_struct_type_di_node<'ll, 'tcx>( // Tuples //=----------------------------------------------------------------------------- -/// Builds the DW_TAG_member debuginfo nodes for the upvars of a closure or generator. -/// For a generator, this will handle upvars shared by all states. +/// Builds the DW_TAG_member debuginfo nodes for the upvars of a closure or coroutine. +/// For a coroutine, this will handle upvars shared by all states. fn build_upvar_field_di_nodes<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, - closure_or_generator_ty: Ty<'tcx>, - closure_or_generator_di_node: &'ll DIType, + closure_or_coroutine_ty: Ty<'tcx>, + closure_or_coroutine_di_node: &'ll DIType, ) -> SmallVec<&'ll DIType> { - let (&def_id, up_var_tys) = match closure_or_generator_ty.kind() { - ty::Coroutine(def_id, args, _) => (def_id, args.as_generator().prefix_tys()), + let (&def_id, up_var_tys) = match closure_or_coroutine_ty.kind() { + ty::Coroutine(def_id, args, _) => (def_id, args.as_coroutine().prefix_tys()), ty::Closure(def_id, args) => (def_id, args.as_closure().upvar_tys()), _ => { bug!( - "build_upvar_field_di_nodes() called with non-closure-or-generator-type: {:?}", - closure_or_generator_ty + "build_upvar_field_di_nodes() called with non-closure-or-coroutine-type: {:?}", + closure_or_coroutine_ty ) } }; @@ -1049,7 +1049,7 @@ fn build_upvar_field_di_nodes<'ll, 'tcx>( ); let capture_names = cx.tcx.closure_saved_names_of_captured_variables(def_id); - let layout = cx.layout_of(closure_or_generator_ty); + let layout = cx.layout_of(closure_or_coroutine_ty); up_var_tys .into_iter() @@ -1058,7 +1058,7 @@ fn build_upvar_field_di_nodes<'ll, 'tcx>( .map(|(index, (up_var_ty, capture_name))| { build_field_di_node( cx, - closure_or_generator_di_node, + closure_or_coroutine_di_node, capture_name.as_str(), cx.size_and_align_of(up_var_ty), layout.fields.offset(index), diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs index cebaeb1611c..ca7bfbeac25 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs @@ -268,18 +268,18 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( ) } -/// A generator debuginfo node looks the same as a that of an enum type. +/// A coroutine debuginfo node looks the same as a that of an enum type. /// /// See [build_enum_type_di_node] for more information. -pub(super) fn build_generator_di_node<'ll, 'tcx>( +pub(super) fn build_coroutine_di_node<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, unique_type_id: UniqueTypeId<'tcx>, ) -> DINodeCreationResult<'ll> { - let generator_type = unique_type_id.expect_ty(); - let generator_type_and_layout = cx.layout_of(generator_type); - let generator_type_name = compute_debuginfo_type_name(cx.tcx, generator_type, false); + let coroutine_type = unique_type_id.expect_ty(); + let coroutine_type_and_layout = cx.layout_of(coroutine_type); + let coroutine_type_name = compute_debuginfo_type_name(cx.tcx, coroutine_type, false); - debug_assert!(!wants_c_like_enum_debuginfo(generator_type_and_layout)); + debug_assert!(!wants_c_like_enum_debuginfo(coroutine_type_and_layout)); type_map::build_type_with_children( cx, @@ -287,24 +287,24 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( cx, type_map::Stub::Union, unique_type_id, - &generator_type_name, - size_and_align_of(generator_type_and_layout), + &coroutine_type_name, + size_and_align_of(coroutine_type_and_layout), NO_SCOPE_METADATA, DIFlags::FlagZero, ), - |cx, generator_type_di_node| match generator_type_and_layout.variants { + |cx, coroutine_type_di_node| match coroutine_type_and_layout.variants { Variants::Multiple { tag_encoding: TagEncoding::Direct, .. } => { - build_union_fields_for_direct_tag_generator( + build_union_fields_for_direct_tag_coroutine( cx, - generator_type_and_layout, - generator_type_di_node, + coroutine_type_and_layout, + coroutine_type_di_node, ) } Variants::Single { .. } | Variants::Multiple { tag_encoding: TagEncoding::Niche { .. }, .. } => { bug!( - "Encountered generator with non-direct-tag layout: {:?}", - generator_type_and_layout + "Encountered coroutine with non-direct-tag layout: {:?}", + coroutine_type_and_layout ) } }, @@ -428,7 +428,7 @@ fn build_union_fields_for_enum<'ll, 'tcx>( }) .collect(); - build_union_fields_for_direct_tag_enum_or_generator( + build_union_fields_for_direct_tag_enum_or_coroutine( cx, enum_type_and_layout, enum_type_di_node, @@ -469,8 +469,8 @@ fn build_variant_names_type_di_node<'ll, 'tcx>( fn build_variant_struct_wrapper_type_di_node<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, - enum_or_generator_type_and_layout: TyAndLayout<'tcx>, - enum_or_generator_type_di_node: &'ll DIType, + enum_or_coroutine_type_and_layout: TyAndLayout<'tcx>, + enum_or_coroutine_type_di_node: &'ll DIType, variant_index: VariantIdx, untagged_variant_index: Option<VariantIdx>, variant_struct_type_di_node: &'ll DIType, @@ -486,13 +486,13 @@ fn build_variant_struct_wrapper_type_di_node<'ll, 'tcx>( Stub::Struct, UniqueTypeId::for_enum_variant_struct_type_wrapper( cx.tcx, - enum_or_generator_type_and_layout.ty, + enum_or_coroutine_type_and_layout.ty, variant_index, ), &variant_struct_wrapper_type_name(variant_index), // NOTE: We use size and align of enum_type, not from variant_layout: - size_and_align_of(enum_or_generator_type_and_layout), - Some(enum_or_generator_type_di_node), + size_and_align_of(enum_or_coroutine_type_and_layout), + Some(enum_or_coroutine_type_di_node), DIFlags::FlagZero, ), |cx, wrapper_struct_type_di_node| { @@ -535,7 +535,7 @@ fn build_variant_struct_wrapper_type_di_node<'ll, 'tcx>( cx, wrapper_struct_type_di_node, "value", - size_and_align_of(enum_or_generator_type_and_layout), + size_and_align_of(enum_or_coroutine_type_and_layout), Size::ZERO, DIFlags::FlagZero, variant_struct_type_di_node, @@ -662,40 +662,40 @@ fn split_128(value: u128) -> Split128 { Split128 { hi: (value >> 64) as u64, lo: value as u64 } } -fn build_union_fields_for_direct_tag_generator<'ll, 'tcx>( +fn build_union_fields_for_direct_tag_coroutine<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, - generator_type_and_layout: TyAndLayout<'tcx>, - generator_type_di_node: &'ll DIType, + coroutine_type_and_layout: TyAndLayout<'tcx>, + coroutine_type_di_node: &'ll DIType, ) -> SmallVec<&'ll DIType> { let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } = - generator_type_and_layout.variants + coroutine_type_and_layout.variants else { bug!("This function only supports layouts with directly encoded tags.") }; - let (generator_def_id, generator_args) = match generator_type_and_layout.ty.kind() { - &ty::Coroutine(def_id, args, _) => (def_id, args.as_generator()), + let (coroutine_def_id, coroutine_args) = match coroutine_type_and_layout.ty.kind() { + &ty::Coroutine(def_id, args, _) => (def_id, args.as_coroutine()), _ => unreachable!(), }; - let generator_layout = cx.tcx.optimized_mir(generator_def_id).generator_layout().unwrap(); + let coroutine_layout = cx.tcx.optimized_mir(coroutine_def_id).coroutine_layout().unwrap(); - let common_upvar_names = cx.tcx.closure_saved_names_of_captured_variables(generator_def_id); - let variant_range = generator_args.variant_range(generator_def_id, cx.tcx); + let common_upvar_names = cx.tcx.closure_saved_names_of_captured_variables(coroutine_def_id); + let variant_range = coroutine_args.variant_range(coroutine_def_id, cx.tcx); let variant_count = (variant_range.start.as_u32()..variant_range.end.as_u32()).len(); - let tag_base_type = tag_base_type(cx, generator_type_and_layout); + let tag_base_type = tag_base_type(cx, coroutine_type_and_layout); let variant_names_type_di_node = build_variant_names_type_di_node( cx, - generator_type_di_node, + coroutine_type_di_node, variant_range .clone() .map(|variant_index| (variant_index, CoroutineArgs::variant_name(variant_index))), ); let discriminants: IndexVec<VariantIdx, DiscrResult> = { - let discriminants_iter = generator_args.discriminants(generator_def_id, cx.tcx); + let discriminants_iter = coroutine_args.discriminants(coroutine_def_id, cx.tcx); let mut discriminants: IndexVec<VariantIdx, DiscrResult> = IndexVec::with_capacity(variant_count); for (variant_index, discr) in discriminants_iter { @@ -709,16 +709,16 @@ fn build_union_fields_for_direct_tag_generator<'ll, 'tcx>( // Build the type node for each field. let variant_field_infos: SmallVec<VariantFieldInfo<'ll>> = variant_range .map(|variant_index| { - let variant_struct_type_di_node = super::build_generator_variant_struct_type_di_node( + let variant_struct_type_di_node = super::build_coroutine_variant_struct_type_di_node( cx, variant_index, - generator_type_and_layout, - generator_type_di_node, - generator_layout, + coroutine_type_and_layout, + coroutine_type_di_node, + coroutine_layout, &common_upvar_names, ); - let span = generator_layout.variant_source_info[variant_index].span; + let span = coroutine_layout.variant_source_info[variant_index].span; let source_info = if !span.is_dummy() { let loc = cx.lookup_debug_loc(span.lo()); Some((file_metadata(cx, &loc.file), loc.line as c_uint)) @@ -735,10 +735,10 @@ fn build_union_fields_for_direct_tag_generator<'ll, 'tcx>( }) .collect(); - build_union_fields_for_direct_tag_enum_or_generator( + build_union_fields_for_direct_tag_enum_or_coroutine( cx, - generator_type_and_layout, - generator_type_di_node, + coroutine_type_and_layout, + coroutine_type_di_node, &variant_field_infos[..], variant_names_type_di_node, tag_base_type, @@ -747,9 +747,9 @@ fn build_union_fields_for_direct_tag_generator<'ll, 'tcx>( ) } -/// This is a helper function shared between enums and generators that makes sure fields have the +/// This is a helper function shared between enums and coroutines that makes sure fields have the /// expect names. -fn build_union_fields_for_direct_tag_enum_or_generator<'ll, 'tcx>( +fn build_union_fields_for_direct_tag_enum_or_coroutine<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, enum_type_and_layout: TyAndLayout<'tcx>, enum_type_di_node: &'ll DIType, diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs index 9fccd925292..df1df6d197e 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs @@ -66,14 +66,14 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( } } -pub(super) fn build_generator_di_node<'ll, 'tcx>( +pub(super) fn build_coroutine_di_node<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, unique_type_id: UniqueTypeId<'tcx>, ) -> DINodeCreationResult<'ll> { if cpp_like_debuginfo(cx.tcx) { - cpp_like::build_generator_di_node(cx, unique_type_id) + cpp_like::build_coroutine_di_node(cx, unique_type_id) } else { - native::build_generator_di_node(cx, unique_type_id) + native::build_coroutine_di_node(cx, unique_type_id) } } @@ -101,7 +101,7 @@ fn build_c_style_enum_di_node<'ll, 'tcx>( } } -/// Extract the type with which we want to describe the tag of the given enum or generator. +/// Extract the type with which we want to describe the tag of the given enum or coroutine. fn tag_base_type<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, enum_type_and_layout: TyAndLayout<'tcx>, @@ -300,8 +300,8 @@ fn build_enum_variant_struct_type_di_node<'ll, 'tcx>( .di_node } -/// Build the struct type for describing a single generator state. -/// See [build_generator_variant_struct_type_di_node]. +/// Build the struct type for describing a single coroutine state. +/// See [build_coroutine_variant_struct_type_di_node]. /// /// ```txt /// @@ -317,25 +317,25 @@ fn build_enum_variant_struct_type_di_node<'ll, 'tcx>( /// ---> DW_TAG_structure_type (type of variant 3) /// /// ``` -pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>( +pub fn build_coroutine_variant_struct_type_di_node<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, variant_index: VariantIdx, - generator_type_and_layout: TyAndLayout<'tcx>, - generator_type_di_node: &'ll DIType, - generator_layout: &CoroutineLayout<'tcx>, + coroutine_type_and_layout: TyAndLayout<'tcx>, + coroutine_type_di_node: &'ll DIType, + coroutine_layout: &CoroutineLayout<'tcx>, common_upvar_names: &IndexSlice<FieldIdx, Symbol>, ) -> &'ll DIType { let variant_name = CoroutineArgs::variant_name(variant_index); let unique_type_id = UniqueTypeId::for_enum_variant_struct_type( cx.tcx, - generator_type_and_layout.ty, + coroutine_type_and_layout.ty, variant_index, ); - let variant_layout = generator_type_and_layout.for_variant(cx, variant_index); + let variant_layout = coroutine_type_and_layout.for_variant(cx, variant_index); - let generator_args = match generator_type_and_layout.ty.kind() { - ty::Coroutine(_, args, _) => args.as_generator(), + let coroutine_args = match coroutine_type_and_layout.ty.kind() { + ty::Coroutine(_, args, _) => args.as_coroutine(), _ => unreachable!(), }; @@ -346,17 +346,17 @@ pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>( Stub::Struct, unique_type_id, &variant_name, - size_and_align_of(generator_type_and_layout), - Some(generator_type_di_node), + size_and_align_of(coroutine_type_and_layout), + Some(coroutine_type_di_node), DIFlags::FlagZero, ), |cx, variant_struct_type_di_node| { // Fields that just belong to this variant/state let state_specific_fields: SmallVec<_> = (0..variant_layout.fields.count()) .map(|field_index| { - let generator_saved_local = generator_layout.variant_fields[variant_index] + let coroutine_saved_local = coroutine_layout.variant_fields[variant_index] [FieldIdx::from_usize(field_index)]; - let field_name_maybe = generator_layout.field_names[generator_saved_local]; + let field_name_maybe = coroutine_layout.field_names[coroutine_saved_local]; let field_name = field_name_maybe .as_ref() .map(|s| Cow::from(s.as_str())) @@ -377,7 +377,7 @@ pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>( .collect(); // Fields that are common to all states - let common_fields: SmallVec<_> = generator_args + let common_fields: SmallVec<_> = coroutine_args .prefix_tys() .iter() .zip(common_upvar_names) @@ -388,7 +388,7 @@ pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>( variant_struct_type_di_node, upvar_name.as_str(), cx.size_and_align_of(upvar_ty), - generator_type_and_layout.fields.offset(index), + coroutine_type_and_layout.fields.offset(index), DIFlags::FlagZero, type_di_node(cx, upvar_ty), ) @@ -397,7 +397,7 @@ pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>( state_specific_fields.into_iter().chain(common_fields.into_iter()).collect() }, - |cx| build_generic_type_param_di_nodes(cx, generator_type_and_layout.ty), + |cx| build_generic_type_param_di_nodes(cx, coroutine_type_and_layout.ty), ) .di_node } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs index 9588a7ec128..7eff52b857f 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs @@ -110,12 +110,12 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( ) } -/// Build the debuginfo node for a generator environment. It looks the same as the debuginfo for +/// Build the debuginfo node for a coroutine environment. It looks the same as the debuginfo for /// an enum. See [build_enum_type_di_node] for more information. /// /// ```txt /// -/// ---> DW_TAG_structure_type (top-level type for the generator) +/// ---> DW_TAG_structure_type (top-level type for the coroutine) /// DW_TAG_variant_part (variant part) /// DW_AT_discr (reference to discriminant DW_TAG_member) /// DW_TAG_member (discriminant member) @@ -127,21 +127,21 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( /// DW_TAG_structure_type (type of variant 3) /// /// ``` -pub(super) fn build_generator_di_node<'ll, 'tcx>( +pub(super) fn build_coroutine_di_node<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, unique_type_id: UniqueTypeId<'tcx>, ) -> DINodeCreationResult<'ll> { - let generator_type = unique_type_id.expect_ty(); - let &ty::Coroutine(generator_def_id, _, _) = generator_type.kind() else { - bug!("build_generator_di_node() called with non-generator type: `{:?}`", generator_type) + let coroutine_type = unique_type_id.expect_ty(); + let &ty::Coroutine(coroutine_def_id, _, _) = coroutine_type.kind() else { + bug!("build_coroutine_di_node() called with non-coroutine type: `{:?}`", coroutine_type) }; - let containing_scope = get_namespace_for_item(cx, generator_def_id); - let generator_type_and_layout = cx.layout_of(generator_type); + let containing_scope = get_namespace_for_item(cx, coroutine_def_id); + let coroutine_type_and_layout = cx.layout_of(coroutine_type); - debug_assert!(!wants_c_like_enum_debuginfo(generator_type_and_layout)); + debug_assert!(!wants_c_like_enum_debuginfo(coroutine_type_and_layout)); - let generator_type_name = compute_debuginfo_type_name(cx.tcx, generator_type, false); + let coroutine_type_name = compute_debuginfo_type_name(cx.tcx, coroutine_type, false); type_map::build_type_with_children( cx, @@ -149,26 +149,26 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( cx, Stub::Struct, unique_type_id, - &generator_type_name, - size_and_align_of(generator_type_and_layout), + &coroutine_type_name, + size_and_align_of(coroutine_type_and_layout), Some(containing_scope), DIFlags::FlagZero, ), - |cx, generator_type_di_node| { - let generator_layout = - cx.tcx.optimized_mir(generator_def_id).generator_layout().unwrap(); + |cx, coroutine_type_di_node| { + let coroutine_layout = + cx.tcx.optimized_mir(coroutine_def_id).coroutine_layout().unwrap(); let Variants::Multiple { tag_encoding: TagEncoding::Direct, ref variants, .. } = - generator_type_and_layout.variants + coroutine_type_and_layout.variants else { bug!( - "Encountered generator with non-direct-tag layout: {:?}", - generator_type_and_layout + "Encountered coroutine with non-direct-tag layout: {:?}", + coroutine_type_and_layout ) }; let common_upvar_names = - cx.tcx.closure_saved_names_of_captured_variables(generator_def_id); + cx.tcx.closure_saved_names_of_captured_variables(coroutine_def_id); // Build variant struct types let variant_struct_type_di_nodes: SmallVec<_> = variants @@ -179,7 +179,7 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( // with enums? let variant_name = format!("{}", variant_index.as_usize()).into(); - let span = generator_layout.variant_source_info[variant_index].span; + let span = coroutine_layout.variant_source_info[variant_index].span; let source_info = if !span.is_dummy() { let loc = cx.lookup_debug_loc(span.lo()); Some((file_metadata(cx, &loc.file), loc.line)) @@ -191,12 +191,12 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( variant_index, variant_name, variant_struct_type_di_node: - super::build_generator_variant_struct_type_di_node( + super::build_coroutine_variant_struct_type_di_node( cx, variant_index, - generator_type_and_layout, - generator_type_di_node, - generator_layout, + coroutine_type_and_layout, + coroutine_type_di_node, + coroutine_layout, &common_upvar_names, ), source_info, @@ -206,18 +206,18 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( smallvec![build_enum_variant_part_di_node( cx, - generator_type_and_layout, - generator_type_di_node, + coroutine_type_and_layout, + coroutine_type_di_node, &variant_struct_type_di_nodes[..], )] }, - // We don't seem to be emitting generic args on the generator type, it seems. Rather + // We don't seem to be emitting generic args on the coroutine type, it seems. Rather // they get attached to the struct type of each variant. NO_GENERICS, ) } -/// Builds the DW_TAG_variant_part of an enum or generator debuginfo node: +/// Builds the DW_TAG_variant_part of an enum or coroutine debuginfo node: /// /// ```txt /// DW_TAG_structure_type (top-level type for enum) @@ -306,10 +306,10 @@ fn build_enum_variant_part_di_node<'ll, 'tcx>( /// ``` fn build_discr_member_di_node<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, - enum_or_generator_type_and_layout: TyAndLayout<'tcx>, - enum_or_generator_type_di_node: &'ll DIType, + enum_or_coroutine_type_and_layout: TyAndLayout<'tcx>, + enum_or_coroutine_type_di_node: &'ll DIType, ) -> Option<&'ll DIType> { - let tag_name = match enum_or_generator_type_and_layout.ty.kind() { + let tag_name = match enum_or_coroutine_type_and_layout.ty.kind() { ty::Coroutine(..) => "__state", _ => "", }; @@ -320,14 +320,14 @@ fn build_discr_member_di_node<'ll, 'tcx>( // In LLVM IR the wrong scope will be listed but when DWARF is // generated from it, the DW_TAG_member will be a child the // DW_TAG_variant_part. - let containing_scope = enum_or_generator_type_di_node; + let containing_scope = enum_or_coroutine_type_di_node; - match enum_or_generator_type_and_layout.layout.variants() { + match enum_or_coroutine_type_and_layout.layout.variants() { // A single-variant enum has no discriminant. &Variants::Single { .. } => None, &Variants::Multiple { tag_field, .. } => { - let tag_base_type = tag_base_type(cx, enum_or_generator_type_and_layout); + let tag_base_type = tag_base_type(cx, enum_or_coroutine_type_and_layout); let (size, align) = cx.size_and_align_of(tag_base_type); unsafe { @@ -340,7 +340,7 @@ fn build_discr_member_di_node<'ll, 'tcx>( UNKNOWN_LINE_NUMBER, size.bits(), align.bits() as u32, - enum_or_generator_type_and_layout.fields.offset(tag_field).bits(), + enum_or_coroutine_type_and_layout.fields.offset(tag_field).bits(), DIFlags::FlagArtificial, type_di_node(cx, tag_base_type), )) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs index e30622cbdce..1aec65cf949 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs @@ -43,7 +43,7 @@ pub(super) enum UniqueTypeId<'tcx> { /// The ID of a regular type as it shows up at the language level. Ty(Ty<'tcx>, private::HiddenZst), /// The ID for the single DW_TAG_variant_part nested inside the top-level - /// DW_TAG_structure_type that describes enums and generators. + /// DW_TAG_structure_type that describes enums and coroutines. VariantPart(Ty<'tcx>, private::HiddenZst), /// The ID for the artificial struct type describing a single enum variant. VariantStructType(Ty<'tcx>, VariantIdx, private::HiddenZst), diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index d874b3ab99d..c8bf7286edf 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -342,7 +342,7 @@ impl<'ll, 'tcx> DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { // We look up the generics of the enclosing function and truncate the args // to their length in order to cut off extra stuff that might be in there for - // closures or generators. + // closures or coroutines. let generics = tcx.generics_of(enclosing_fn_def_id); let args = instance.args.truncate_to(tcx, generics); diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 8cd627fc619..aad6916ec91 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -399,22 +399,22 @@ fn push_debuginfo_type_name<'tcx>( visited.remove(&t); } ty::Closure(def_id, args) | ty::Coroutine(def_id, args, ..) => { - // Name will be "{closure_env#0}<T1, T2, ...>", "{generator_env#0}<T1, T2, ...>", or + // Name will be "{closure_env#0}<T1, T2, ...>", "{coroutine_env#0}<T1, T2, ...>", or // "{async_fn_env#0}<T1, T2, ...>", etc. // In the case of cpp-like debuginfo, the name additionally gets wrapped inside of // an artificial `enum2$<>` type, as defined in msvc_enum_fallback(). - if cpp_like_debuginfo && t.is_generator() { + if cpp_like_debuginfo && t.is_coroutine() { let ty_and_layout = tcx.layout_of(ParamEnv::reveal_all().and(t)).unwrap(); msvc_enum_fallback( ty_and_layout, &|output, visited| { - push_closure_or_generator_name(tcx, def_id, args, true, output, visited); + push_closure_or_coroutine_name(tcx, def_id, args, true, output, visited); }, output, visited, ); } else { - push_closure_or_generator_name(tcx, def_id, args, qualified, output, visited); + push_closure_or_coroutine_name(tcx, def_id, args, qualified, output, visited); } } // Type parameters from polymorphized functions. @@ -558,12 +558,12 @@ pub fn push_item_name(tcx: TyCtxt<'_>, def_id: DefId, qualified: bool, output: & push_unqualified_item_name(tcx, def_id, def_key.disambiguated_data, output); } -fn generator_kind_label(generator_kind: Option<CoroutineKind>) -> &'static str { - match generator_kind { +fn coroutine_kind_label(coroutine_kind: Option<CoroutineKind>) -> &'static str { + match coroutine_kind { Some(CoroutineKind::Async(AsyncCoroutineKind::Block)) => "async_block", Some(CoroutineKind::Async(AsyncCoroutineKind::Closure)) => "async_closure", Some(CoroutineKind::Async(AsyncCoroutineKind::Fn)) => "async_fn", - Some(CoroutineKind::Gen) => "generator", + Some(CoroutineKind::Gen) => "coroutine", None => "closure", } } @@ -592,7 +592,7 @@ fn push_unqualified_item_name( output.push_str(tcx.crate_name(def_id.krate).as_str()); } DefPathData::ClosureExpr => { - let label = generator_kind_label(tcx.generator_kind(def_id)); + let label = coroutine_kind_label(tcx.coroutine_kind(def_id)); push_disambiguated_special_name( label, @@ -707,7 +707,7 @@ pub fn push_generic_params<'tcx>( push_generic_params_internal(tcx, args, def_id, output, &mut visited); } -fn push_closure_or_generator_name<'tcx>( +fn push_closure_or_coroutine_name<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>, @@ -715,10 +715,10 @@ fn push_closure_or_generator_name<'tcx>( output: &mut String, visited: &mut FxHashSet<Ty<'tcx>>, ) { - // Name will be "{closure_env#0}<T1, T2, ...>", "{generator_env#0}<T1, T2, ...>", or + // Name will be "{closure_env#0}<T1, T2, ...>", "{coroutine_env#0}<T1, T2, ...>", or // "{async_fn_env#0}<T1, T2, ...>", etc. let def_key = tcx.def_key(def_id); - let generator_kind = tcx.generator_kind(def_id); + let coroutine_kind = tcx.coroutine_kind(def_id); if qualified { let parent_def_id = DefId { index: def_key.parent.unwrap(), ..def_id }; @@ -727,7 +727,7 @@ fn push_closure_or_generator_name<'tcx>( } let mut label = String::with_capacity(20); - write!(&mut label, "{}_env", generator_kind_label(generator_kind)).unwrap(); + write!(&mut label, "{}_env", coroutine_kind_label(coroutine_kind)).unwrap(); push_disambiguated_special_name( &label, @@ -736,7 +736,7 @@ fn push_closure_or_generator_name<'tcx>( output, ); - // We also need to add the generic arguments of the async fn/generator or + // We also need to add the generic arguments of the async fn/coroutine or // the enclosing function (for closures or async blocks), so that we end // up with a unique name for every instantiation. @@ -745,7 +745,7 @@ fn push_closure_or_generator_name<'tcx>( let generics = tcx.generics_of(enclosing_fn_def_id); // Truncate the args to the length of the above generics. This will cut off - // anything closure- or generator-specific. + // anything closure- or coroutine-specific. let args = args.truncate_to(tcx, generics); push_generic_params_internal(tcx, args, enclosing_fn_def_id, output, visited); } diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index f35cf282072..caade768795 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -1266,7 +1266,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { mergeable_succ(), ), mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => { - bug!("generator ops in codegen") + bug!("coroutine ops in codegen") } mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => { bug!("borrowck false edges in codegen") diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 166d3d45e79..0d0ebe6f390 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -534,8 +534,8 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, OverflowNeg(op) => OverflowNeg(eval_to_int(op)?), DivisionByZero(op) => DivisionByZero(eval_to_int(op)?), RemainderByZero(op) => RemainderByZero(eval_to_int(op)?), - ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind), - ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind), + ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind), + ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind), MisalignedPointerDereference { ref required, ref found } => { MisalignedPointerDereference { required: eval_to_int(required)?, diff --git a/compiler/rustc_const_eval/src/interpret/discriminant.rs b/compiler/rustc_const_eval/src/interpret/discriminant.rs index 1f347aca65f..8dab45d65ee 100644 --- a/compiler/rustc_const_eval/src/interpret/discriminant.rs +++ b/compiler/rustc_const_eval/src/interpret/discriminant.rs @@ -1,4 +1,4 @@ -//! Functions for reading and writing discriminants of multi-variant layouts (enums and generators). +//! Functions for reading and writing discriminants of multi-variant layouts (enums and coroutines). use rustc_middle::ty::layout::{LayoutOf, PrimitiveExt, TyAndLayout}; use rustc_middle::{mir, ty}; @@ -171,10 +171,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits) } ty::Coroutine(def_id, args, _) => { - let args = args.as_generator(); + let args = args.as_coroutine(); args.discriminants(def_id, *self.tcx).find(|(_, var)| var.val == discr_bits) } - _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"), + _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-coroutine"), } .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?; // Return the cast value, and the index. diff --git a/compiler/rustc_const_eval/src/interpret/util.rs b/compiler/rustc_const_eval/src/interpret/util.rs index a087d0ac70d..416443f5f4d 100644 --- a/compiler/rustc_const_eval/src/interpret/util.rs +++ b/compiler/rustc_const_eval/src/interpret/util.rs @@ -42,10 +42,10 @@ where let index = index .try_into() .expect("more generic parameters than can fit into a `u32`"); - // Only recurse when generic parameters in fns, closures and generators + // Only recurse when generic parameters in fns, closures and coroutines // are used and have to be instantiated. // - // Just in case there are closures or generators within this subst, + // Just in case there are closures or coroutines within this subst, // recurse. if unused_params.is_used(index) && subst.has_param() { return subst.visit_with(self); diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 6c541d0868a..56b7b6bf826 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -171,8 +171,8 @@ fn write_path(out: &mut String, path: &[PathElem]) { Field(name) => write!(out, ".{name}"), EnumTag => write!(out, ".<enum-tag>"), Variant(name) => write!(out, ".<enum-variant({name})>"), - CoroutineTag => write!(out, ".<generator-tag>"), - CoroutineState(idx) => write!(out, ".<generator-state({})>", idx.index()), + CoroutineTag => write!(out, ".<coroutine-tag>"), + CoroutineState(idx) => write!(out, ".<coroutine-state({})>", idx.index()), CapturedVar(name) => write!(out, ".<captured-var({name})>"), TupleElem(idx) => write!(out, ".{idx}"), ArrayElem(idx) => write!(out, "[{idx}]"), @@ -216,7 +216,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' // Now we know we are projecting to a field, so figure out which one. match layout.ty.kind() { - // generators and closures. + // coroutines and closures. ty::Closure(def_id, _) | ty::Coroutine(def_id, _, _) => { let mut name = None; // FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar @@ -225,7 +225,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' let captures = self.ecx.tcx.closure_captures(local_def_id); if let Some(captured_place) = captures.get(field) { // Sometimes the index is beyond the number of upvars (seen - // for a generator). + // for a coroutine). let var_hir_id = captured_place.get_root_variable(); let node = self.ecx.tcx.hir().get(var_hir_id); if let hir::Node::Pat(pat) = node { diff --git a/compiler/rustc_const_eval/src/transform/check_consts/check.rs b/compiler/rustc_const_eval/src/transform/check_consts/check.rs index e0acd695b34..ade1d5726b3 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/check.rs @@ -247,7 +247,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { // `async` functions cannot be `const fn`. This is checked during AST lowering, so there's // no need to emit duplicate errors here. - if self.ccx.is_async() || body.generator.is_some() { + if self.ccx.is_async() || body.coroutine.is_some() { tcx.sess.delay_span_bug(body.span, "`async` functions cannot be `const fn`"); return; } @@ -464,10 +464,10 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { Rvalue::Aggregate(kind, ..) => { if let AggregateKind::Coroutine(def_id, ..) = kind.as_ref() - && let Some(generator_kind @ hir::CoroutineKind::Async(..)) = - self.tcx.generator_kind(def_id) + && let Some(coroutine_kind @ hir::CoroutineKind::Async(..)) = + self.tcx.coroutine_kind(def_id) { - self.check_op(ops::Coroutine(generator_kind)); + self.check_op(ops::Coroutine(coroutine_kind)); } } diff --git a/compiler/rustc_const_eval/src/transform/promote_consts.rs b/compiler/rustc_const_eval/src/transform/promote_consts.rs index 8ede3bdd2b6..05902976638 100644 --- a/compiler/rustc_const_eval/src/transform/promote_consts.rs +++ b/compiler/rustc_const_eval/src/transform/promote_consts.rs @@ -970,7 +970,7 @@ pub fn promote_candidates<'tcx>( 0, vec![], body.span, - body.generator_kind(), + body.coroutine_kind(), body.tainted_by_errors, ); promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial); diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index 480327503ea..b70a342aa15 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -472,11 +472,11 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> { self.check_unwind_edge(location, *unwind); } TerminatorKind::Yield { resume, drop, .. } => { - if self.body.generator.is_none() { - self.fail(location, "`Yield` cannot appear outside generator bodies"); + if self.body.coroutine.is_none() { + self.fail(location, "`Yield` cannot appear outside coroutine bodies"); } if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) { - self.fail(location, "`Yield` should have been replaced by generator lowering"); + self.fail(location, "`Yield` should have been replaced by coroutine lowering"); } self.check_edge(location, *resume, EdgeKind::Normal); if let Some(drop) = drop { @@ -510,13 +510,13 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> { self.check_unwind_edge(location, *unwind); } TerminatorKind::CoroutineDrop => { - if self.body.generator.is_none() { - self.fail(location, "`CoroutineDrop` cannot appear outside generator bodies"); + if self.body.coroutine.is_none() { + self.fail(location, "`CoroutineDrop` cannot appear outside coroutine bodies"); } if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Initial) { self.fail( location, - "`CoroutineDrop` should have been replaced by generator lowering", + "`CoroutineDrop` should have been replaced by coroutine lowering", ); } } @@ -724,10 +724,10 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { self.tcx.optimized_mir(def_id) }; - let Some(layout) = gen_body.generator_layout() else { + let Some(layout) = gen_body.coroutine_layout() else { self.fail( location, - format!("No generator layout for {parent_ty:?}"), + format!("No coroutine layout for {parent_ty:?}"), ); return; }; @@ -747,7 +747,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ty::EarlyBinder::bind(f_ty.ty).instantiate(self.tcx, args) } else { - let Some(&f_ty) = args.as_generator().prefix_tys().get(f.index()) + let Some(&f_ty) = args.as_coroutine().prefix_tys().get(f.index()) else { fail_out_of_bounds(self, location); return; @@ -1215,7 +1215,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { self.fail( location, format!( - "`SetDiscriminant` is only allowed on ADTs and generators, not {pty:?}" + "`SetDiscriminant` is only allowed on ADTs and coroutines, not {pty:?}" ), ); } diff --git a/compiler/rustc_feature/src/removed.rs b/compiler/rustc_feature/src/removed.rs index 339f596144c..52746dda358 100644 --- a/compiler/rustc_feature/src/removed.rs +++ b/compiler/rustc_feature/src/removed.rs @@ -42,7 +42,7 @@ declare_features! ( Some("subsumed by `.await` syntax")), /// Allows using the `box $expr` syntax. (removed, box_syntax, "1.70.0", Some(49733), None, Some("replaced with `#[rustc_box]`")), - /// Allows capturing disjoint fields in a closure/generator (RFC 2229). + /// Allows capturing disjoint fields in a closure/coroutine (RFC 2229). (removed, capture_disjoint_fields, "1.49.0", Some(53488), None, Some("stabilized in Rust 2021")), /// Allows comparing raw pointers during const eval. (removed, const_compare_raw_pointers, "1.46.0", Some(53020), None, diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 27cdf1ba831..8185a8a3e43 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -371,9 +371,9 @@ declare_features! ( (unstable, cfg_version, "1.45.0", Some(64796), None), /// Allows to use the `#[cfi_encoding = ""]` attribute. (unstable, cfi_encoding, "1.71.0", Some(89653), None), - /// Allows `for<...>` on closures and generators. + /// Allows `for<...>` on closures and coroutines. (unstable, closure_lifetime_binder, "1.64.0", Some(97362), None), - /// Allows `#[track_caller]` on closures and generators. + /// Allows `#[track_caller]` on closures and coroutines. (unstable, closure_track_caller, "1.57.0", Some(87417), None), /// Allows to use the `#[cmse_nonsecure_entry]` attribute. (unstable, cmse_nonsecure_entry, "1.48.0", Some(75835), None), @@ -399,6 +399,10 @@ declare_features! ( (unstable, const_trait_impl, "1.42.0", Some(67792), None), /// Allows the `?` operator in const contexts. (unstable, const_try, "1.56.0", Some(74935), None), + /// Allows coroutines to be cloned. + (unstable, coroutine_clone, "1.65.0", Some(95360), None), + /// Allows defining coroutines. + (unstable, coroutines, "1.21.0", Some(43122), None), /// Allows function attribute `#[coverage(on/off)]`, to control coverage /// instrumentation of that function. (unstable, coverage_attribute, "1.74.0", Some(84605), None), @@ -451,10 +455,6 @@ declare_features! ( (unstable, ffi_returns_twice, "1.34.0", Some(58314), None), /// Allows using `#[repr(align(...))]` on function items (unstable, fn_align, "1.53.0", Some(82232), None), - /// Allows generators to be cloned. - (unstable, generator_clone, "1.65.0", Some(95360), None), - /// Allows defining generators. - (unstable, generators, "1.21.0", Some(43122), None), /// Infer generic args for both consts and types. (unstable, generic_arg_infer, "1.55.0", Some(85077), None), /// An extension to the `generic_associated_types` feature, allowing incomplete features. diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index 3c7d158c9ad..ed1dc751fba 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -126,7 +126,7 @@ impl DefKind { /// /// If you have access to `TyCtxt`, use `TyCtxt::def_descr` or /// `TyCtxt::def_kind_descr` instead, because they give better - /// information for generators and associated functions. + /// information for coroutines and associated functions. pub fn descr(self, def_id: DefId) -> &'static str { match self { DefKind::Fn => "function", @@ -161,7 +161,7 @@ impl DefKind { DefKind::Field => "field", DefKind::Impl { .. } => "implementation", DefKind::Closure => "closure", - DefKind::Coroutine => "generator", + DefKind::Coroutine => "coroutine", DefKind::ExternCrate => "extern crate", DefKind::GlobalAsm => "global assembly block", } @@ -171,7 +171,7 @@ impl DefKind { /// /// If you have access to `TyCtxt`, use `TyCtxt::def_descr_article` or /// `TyCtxt::def_kind_descr_article` instead, because they give better - /// information for generators and associated functions. + /// information for coroutines and associated functions. pub fn article(&self) -> &'static str { match *self { DefKind::AssocTy diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index f60e312937c..cace819c890 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1485,7 +1485,7 @@ pub struct BodyId { /// /// - an `params` array containing the `(x, y)` pattern /// - a `value` containing the `x + y` expression (maybe wrapped in a block) -/// - `generator_kind` would be `None` +/// - `coroutine_kind` would be `None` /// /// All bodies have an **owner**, which can be accessed via the HIR /// map using `body_owner_def_id()`. @@ -1493,7 +1493,7 @@ pub struct BodyId { pub struct Body<'hir> { pub params: &'hir [Param<'hir>], pub value: &'hir Expr<'hir>, - pub generator_kind: Option<CoroutineKind>, + pub coroutine_kind: Option<CoroutineKind>, } impl<'hir> Body<'hir> { @@ -1501,19 +1501,19 @@ impl<'hir> Body<'hir> { BodyId { hir_id: self.value.hir_id } } - pub fn generator_kind(&self) -> Option<CoroutineKind> { - self.generator_kind + pub fn coroutine_kind(&self) -> Option<CoroutineKind> { + self.coroutine_kind } } -/// The type of source expression that caused this generator to be created. +/// The type of source expression that caused this coroutine to be created. #[derive(Clone, PartialEq, Eq, Debug, Copy, Hash)] #[derive(HashStable_Generic, Encodable, Decodable)] pub enum CoroutineKind { /// An explicit `async` block or the body of an async function. Async(AsyncCoroutineKind), - /// A generator literal created via a `yield` inside a closure. + /// A coroutine literal created via a `yield` inside a closure. Gen, } @@ -1521,7 +1521,7 @@ impl fmt::Display for CoroutineKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { CoroutineKind::Async(k) => fmt::Display::fmt(k, f), - CoroutineKind::Gen => f.write_str("generator"), + CoroutineKind::Gen => f.write_str("coroutine"), } } } @@ -1530,12 +1530,12 @@ impl CoroutineKind { pub fn descr(&self) -> &'static str { match self { CoroutineKind::Async(ask) => ask.descr(), - CoroutineKind::Gen => "generator", + CoroutineKind::Gen => "coroutine", } } } -/// In the case of a generator created as part of an async construct, +/// In the case of a coroutine created as part of an async construct, /// which kind of async construct caused it to be created? /// /// This helps error messages but is also used to drive coercions in @@ -2004,7 +2004,7 @@ pub enum ExprKind<'hir> { /// /// The `Span` is the argument block `|...|`. /// - /// This may also be a generator literal or an `async block` as indicated by the + /// This may also be a coroutine literal or an `async block` as indicated by the /// `Option<Movability>`. Closure(&'hir Closure<'hir>), /// A block (e.g., `'label: { ... }`). @@ -2055,7 +2055,7 @@ pub enum ExprKind<'hir> { /// to be repeated; the second is the number of times to repeat it. Repeat(&'hir Expr<'hir>, ArrayLen), - /// A suspension point for generators (i.e., `yield <expr>`). + /// A suspension point for coroutines (i.e., `yield <expr>`). Yield(&'hir Expr<'hir>, YieldSource), /// A placeholder for an expression that wasn't syntactically well formed in some way. @@ -2250,7 +2250,7 @@ impl fmt::Display for YieldSource { impl From<CoroutineKind> for YieldSource { fn from(kind: CoroutineKind) -> Self { match kind { - // Guess based on the kind of the current generator. + // Guess based on the kind of the current coroutine. CoroutineKind::Gen => Self::Yield, CoroutineKind::Async(_) => Self::Await { expr: None }, } diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index d9195a374c2..8a672855989 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -62,7 +62,7 @@ //! respectively. (This follows from RPO respecting CFG domination). //! //! This order consistency is required in a few places in rustc, for -//! example generator inference, and possibly also HIR borrowck. +//! example coroutine inference, and possibly also HIR borrowck. use crate::hir::*; use rustc_ast::walk_list; diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index b13eb3b5e7a..cdfc67d5740 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -211,8 +211,8 @@ language_item_table! { FnOnceOutput, sym::fn_once_output, fn_once_output, Target::AssocTy, GenericRequirement::None; Future, sym::future_trait, future_trait, Target::Trait, GenericRequirement::Exact(0); - CoroutineState, sym::generator_state, gen_state, Target::Enum, GenericRequirement::None; - Coroutine, sym::generator, gen_trait, Target::Trait, GenericRequirement::Minimum(1); + CoroutineState, sym::coroutine_state, gen_state, Target::Enum, GenericRequirement::None; + Coroutine, sym::coroutine, gen_trait, Target::Trait, GenericRequirement::Minimum(1); Unpin, sym::unpin, unpin_trait, Target::Trait, GenericRequirement::None; Pin, sym::pin, pin_type, Target::Struct, GenericRequirement::None; diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 0b410e26add..360d31b863c 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -291,7 +291,7 @@ fn check_opaque_meets_bounds<'tcx>( let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args); - // `ReErased` regions appear in the "parent_args" of closures/generators. + // `ReErased` regions appear in the "parent_args" of closures/coroutines. // We're ignoring them here and replacing them with fresh region variables. // See tests in ui/type-alias-impl-trait/closure_{parent_args,wf_outlives}.rs. // @@ -1446,11 +1446,11 @@ fn opaque_type_cycle_error( { label_match(capture.place.ty(), capture.get_path_span(tcx)); } - // Label any generator locals that capture the opaque + // Label any coroutine locals that capture the opaque if let DefKind::Coroutine = tcx.def_kind(closure_def_id) - && let Some(generator_layout) = tcx.mir_generator_witnesses(closure_def_id) + && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id) { - for interior_ty in &generator_layout.field_tys { + for interior_ty in &coroutine_layout.field_tys { label_match(interior_ty.ty, interior_ty.source_info.span); } } @@ -1464,14 +1464,14 @@ fn opaque_type_cycle_error( err.emit() } -pub(super) fn check_generator_obligations(tcx: TyCtxt<'_>, def_id: LocalDefId) { +pub(super) fn check_coroutine_obligations(tcx: TyCtxt<'_>, def_id: LocalDefId) { debug_assert!(matches!(tcx.def_kind(def_id), DefKind::Coroutine)); let typeck = tcx.typeck(def_id); let param_env = tcx.param_env(def_id); - let generator_interior_predicates = &typeck.generator_interior_predicates[&def_id]; - debug!(?generator_interior_predicates); + let coroutine_interior_predicates = &typeck.coroutine_interior_predicates[&def_id]; + debug!(?coroutine_interior_predicates); let infcx = tcx .infer_ctxt() @@ -1483,15 +1483,15 @@ pub(super) fn check_generator_obligations(tcx: TyCtxt<'_>, def_id: LocalDefId) { .build(); let mut fulfillment_cx = <dyn TraitEngine<'_>>::new(&infcx); - for (predicate, cause) in generator_interior_predicates { + for (predicate, cause) in coroutine_interior_predicates { let obligation = Obligation::new(tcx, cause.clone(), param_env, *predicate); fulfillment_cx.register_predicate_obligation(&infcx, obligation); } if (tcx.features().unsized_locals || tcx.features().unsized_fn_params) - && let Some(generator) = tcx.mir_generator_witnesses(def_id) + && let Some(coroutine) = tcx.mir_coroutine_witnesses(def_id) { - for field_ty in generator.field_tys.iter() { + for field_ty in coroutine.field_tys.iter() { fulfillment_cx.register_bound( &infcx, param_env, diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 5d67a36288c..8da953e6e2e 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -114,7 +114,7 @@ pub fn provide(providers: &mut Providers) { region_scope_tree, collect_return_position_impl_trait_in_trait_tys, compare_impl_const: compare_impl_item::compare_impl_const_raw, - check_generator_obligations: check::check_generator_obligations, + check_coroutine_obligations: check::check_coroutine_obligations, ..*providers }; } diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 463fab93e3f..40b33117f7c 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -598,7 +598,7 @@ fn resolve_local<'tcx>( } // Make sure we visit the initializer first, so expr_and_pat_count remains correct. - // The correct order, as shared between generator_interior, drop_ranges and intravisitor, + // The correct order, as shared between coroutine_interior, drop_ranges and intravisitor, // is to walk initializer, followed by pattern bindings, finally followed by the `else` block. if let Some(expr) = init { visitor.visit_expr(expr); @@ -825,7 +825,7 @@ impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { resolve_local(self, None, Some(&body.value)); } - if body.generator_kind.is_some() { + if body.coroutine_kind.is_some() { self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count); } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index e5908413150..640138a3e5e 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -76,7 +76,7 @@ pub fn provide(providers: &mut Providers) { fn_sig, impl_trait_ref, impl_polarity, - generator_kind, + coroutine_kind, collect_mod_item_types, is_type_alias_impl_trait, ..*providers @@ -1548,12 +1548,12 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( fty } -fn generator_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<hir::CoroutineKind> { +fn coroutine_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<hir::CoroutineKind> { match tcx.hir().get_by_def_id(def_id) { Node::Expr(&rustc_hir::Expr { kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }), .. - }) => tcx.hir().body(body).generator_kind(), + }) => tcx.hir().body(body).coroutine_kind(), _ => None, } } diff --git a/compiler/rustc_hir_typeck/messages.ftl b/compiler/rustc_hir_typeck/messages.ftl index 9950a226333..4fd9391acc3 100644 --- a/compiler/rustc_hir_typeck/messages.ftl +++ b/compiler/rustc_hir_typeck/messages.ftl @@ -150,5 +150,5 @@ hir_typeck_union_pat_multiple_fields = union patterns should have exactly one fi hir_typeck_use_is_empty = consider using the `is_empty` method on `{$expr_ty}` to determine if it contains anything -hir_typeck_yield_expr_outside_of_generator = - yield expression outside of generator literal +hir_typeck_yield_expr_outside_of_coroutine = + yield expression outside of coroutine literal diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 3f6809cf72d..5eb68cf6b28 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -304,7 +304,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::ExprKind::Block(..), ) = (parent_node, callee_node) { - let fn_decl_span = if hir.body(body).generator_kind + let fn_decl_span = if hir.body(body).coroutine_kind == Some(hir::CoroutineKind::Async(hir::AsyncCoroutineKind::Closure)) { // Actually need to unwrap one more layer of HIR to get to diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index a040e2ee9e0..1fb1eb9dbc4 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -31,7 +31,7 @@ pub(super) fn check_fn<'a, 'tcx>( decl: &'tcx hir::FnDecl<'tcx>, fn_def_id: LocalDefId, body: &'tcx hir::Body<'tcx>, - can_be_generator: Option<hir::Movability>, + can_be_coroutine: Option<hir::Movability>, params_can_be_unsized: bool, ) -> Option<CoroutineTypes<'tcx>> { let fn_id = fcx.tcx.hir().local_def_id_to_hir_id(fn_def_id); @@ -55,8 +55,8 @@ pub(super) fn check_fn<'a, 'tcx>( fn_maybe_err(tcx, span, fn_sig.abi); - if let Some(kind) = body.generator_kind - && can_be_generator.is_some() + if let Some(kind) = body.coroutine_kind + && can_be_coroutine.is_some() { let yield_ty = if kind == hir::CoroutineKind::Gen { let yield_ty = fcx.next_ty_var(TypeVariableOrigin { @@ -69,7 +69,7 @@ pub(super) fn check_fn<'a, 'tcx>( Ty::new_unit(tcx) }; - // Resume type defaults to `()` if the generator has no argument. + // Resume type defaults to `()` if the coroutine has no argument. let resume_ty = fn_sig.inputs().get(0).copied().unwrap_or_else(|| Ty::new_unit(tcx)); fcx.resume_yield_tys = Some((resume_ty, yield_ty)); @@ -124,13 +124,13 @@ pub(super) fn check_fn<'a, 'tcx>( fcx.require_type_is_sized(declared_ret_ty, return_or_body_span, traits::SizedReturnType); fcx.check_return_expr(&body.value, false); - // We insert the deferred_generator_interiors entry after visiting the body. - // This ensures that all nested generators appear before the entry of this generator. - // resolve_generator_interiors relies on this property. - let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) { + // We insert the deferred_coroutine_interiors entry after visiting the body. + // This ensures that all nested coroutines appear before the entry of this coroutine. + // resolve_coroutine_interiors relies on this property. + let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_coroutine, body.coroutine_kind) { let interior = fcx .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span }); - fcx.deferred_generator_interiors.borrow_mut().push(( + fcx.deferred_coroutine_interiors.borrow_mut().push(( fn_def_id, body.id(), interior, @@ -142,7 +142,7 @@ pub(super) fn check_fn<'a, 'tcx>( resume_ty, yield_ty, interior, - movability: can_be_generator.unwrap(), + movability: can_be_coroutine.unwrap(), }) } else { None diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 9c6b128dd8d..cf8a4cafbb6 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -84,7 +84,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!(?bound_sig, ?liberated_sig); let mut fcx = FnCtxt::new(self, self.param_env, closure.def_id); - let generator_types = check_fn( + let coroutine_types = check_fn( &mut fcx, liberated_sig, closure.fn_decl, @@ -105,9 +105,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span: self.tcx.def_span(expr_def_id), }); - if let Some(CoroutineTypes { resume_ty, yield_ty, interior, movability }) = generator_types + if let Some(CoroutineTypes { resume_ty, yield_ty, interior, movability }) = coroutine_types { - let generator_args = ty::CoroutineArgs::new( + let coroutine_args = ty::CoroutineArgs::new( self.tcx, ty::CoroutineArgsParts { parent_args, @@ -119,10 +119,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }, ); - return Ty::new_generator( + return Ty::new_coroutine( self.tcx, expr_def_id.to_def_id(), - generator_args.args, + coroutine_args.args, movability, ); } @@ -285,7 +285,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce - /// everything we need to know about a closure or generator. + /// everything we need to know about a closure or coroutine. /// /// The `cause_span` should be the span that caused us to /// have this expected signature, or `None` if we can't readily @@ -306,7 +306,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let is_gen = gen_trait == Some(trait_def_id); if !is_fn && !is_gen { - debug!("not fn or generator"); + debug!("not fn or coroutine"); return None; } @@ -623,7 +623,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let astconv: &dyn AstConv<'_> = self; trace!("decl = {:#?}", decl); - debug!(?body.generator_kind); + debug!(?body.coroutine_kind); let hir_id = self.tcx.hir().local_def_id_to_hir_id(expr_def_id); let bound_vars = self.tcx.late_bound_vars(hir_id); @@ -632,7 +632,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a)); let supplied_return = match decl.output { hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output), - hir::FnRetTy::DefaultReturn(_) => match body.generator_kind { + hir::FnRetTy::DefaultReturn(_) => match body.coroutine_kind { // In the case of the async block that we create for a function body, // we expect the return type of the block to match that of the enclosing // function. @@ -675,7 +675,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.normalize(self.tcx.hir().span(hir_id), result) } - /// Invoked when we are translating the generator that results + /// Invoked when we are translating the coroutine that results /// from desugaring an `async fn`. Returns the "sugared" return /// type of the `async fn` -- that is, the return type that the /// user specified. The "desugared" return type is an `impl @@ -688,7 +688,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { body_def_id: LocalDefId, ) -> Option<Ty<'tcx>> { let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| { - span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn") + span_bug!(self.tcx.def_span(expr_def_id), "async fn coroutine outside of a fn") }); let closure_span = self.tcx.def_span(expr_def_id); @@ -729,7 +729,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Error(_) => return None, _ => span_bug!( closure_span, - "async fn generator return type not an inference variable: {ret_ty}" + "async fn coroutine return type not an inference variable: {ret_ty}" ), }; diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs index d518f79a8db..aff1baa1960 100644 --- a/compiler/rustc_hir_typeck/src/errors.rs +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -62,7 +62,7 @@ pub struct RustCallIncorrectArgs { } #[derive(Diagnostic)] -#[diag(hir_typeck_yield_expr_outside_of_generator, code = "E0627")] +#[diag(hir_typeck_yield_expr_outside_of_coroutine, code = "E0627")] pub struct YieldExprOutsideOfCoroutine { #[primary_span] pub span: Span, diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 8bc66ac5509..6be3ad6577b 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -779,7 +779,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { let closure_def_id = closure_expr.def_id; let upvars = tcx.upvars_mentioned(self.body_owner); - // For purposes of this function, generator and closures are equivalent. + // For purposes of this function, coroutine and closures are equivalent. let body_owner_is_closure = matches!(tcx.hir().body_owner_kind(self.body_owner), hir::BodyOwnerKind::Closure,); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index dbee98b88ba..afa5a3b9379 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -509,25 +509,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { typeck_results.rvalue_scopes = rvalue_scopes; } - /// Unify the inference variables corresponding to generator witnesses, and save all the + /// Unify the inference variables corresponding to coroutine witnesses, and save all the /// predicates that were stalled on those inference variables. /// - /// This process allows to conservatively save all predicates that do depend on the generator - /// interior types, for later processing by `check_generator_obligations`. + /// This process allows to conservatively save all predicates that do depend on the coroutine + /// interior types, for later processing by `check_coroutine_obligations`. /// /// We must not attempt to select obligations after this method has run, or risk query cycle /// ICE. #[instrument(level = "debug", skip(self))] - pub(in super::super) fn resolve_generator_interiors(&self, def_id: DefId) { + pub(in super::super) fn resolve_coroutine_interiors(&self, def_id: DefId) { // Try selecting all obligations that are not blocked on inference variables. - // Once we start unifying generator witnesses, trying to select obligations on them will + // Once we start unifying coroutine witnesses, trying to select obligations on them will // trigger query cycle ICEs, as doing so requires MIR. self.select_obligations_where_possible(|_| {}); - let generators = std::mem::take(&mut *self.deferred_generator_interiors.borrow_mut()); - debug!(?generators); + let coroutines = std::mem::take(&mut *self.deferred_coroutine_interiors.borrow_mut()); + debug!(?coroutines); - for &(expr_def_id, body_id, interior, _) in generators.iter() { + for &(expr_def_id, body_id, interior, _) in coroutines.iter() { debug!(?expr_def_id); // Create the `CoroutineWitness` type that we will unify with `interior`. @@ -535,14 +535,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx, self.tcx.typeck_root_def_id(expr_def_id.to_def_id()), ); - let witness = Ty::new_generator_witness(self.tcx, expr_def_id.to_def_id(), args); + let witness = Ty::new_coroutine_witness(self.tcx, expr_def_id.to_def_id(), args); // Unify `interior` with `witness` and collect all the resulting obligations. let span = self.tcx.hir().body(body_id).value.span; let ok = self .at(&self.misc(span), self.param_env) .eq(DefineOpaqueTypes::No, interior, witness) - .expect("Failed to unify generator interior type"); + .expect("Failed to unify coroutine interior type"); let mut obligations = ok.obligations; // Also collect the obligations that were unstalled by this unification. @@ -553,7 +553,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!(?obligations); self.typeck_results .borrow_mut() - .generator_interior_predicates + .coroutine_interior_predicates .insert(expr_def_id, obligations); } } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 9f1800b45c3..33dfa16a651 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -367,13 +367,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { continue; } - // For this check, we do *not* want to treat async generator closures (async blocks) + // For this check, we do *not* want to treat async coroutine closures (async blocks) // as proper closures. Doing so would regress type inference when feeding // the return value of an argument-position async block to an argument-position // closure wrapped in a block. // See <https://github.com/rust-lang/rust/issues/112225>. let is_closure = if let ExprKind::Closure(closure) = arg.kind { - !tcx.generator_is_async(closure.def_id.to_def_id()) + !tcx.coroutine_is_async(closure.def_id.to_def_id()) } else { false }; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 6dbee3f3936..04220397872 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -534,7 +534,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } ty::Coroutine(def_id, ..) if matches!( - self.tcx.generator_kind(def_id), + self.tcx.coroutine_kind(def_id), Some(CoroutineKind::Async(AsyncCoroutineKind::Closure)) ) => { diff --git a/compiler/rustc_hir_typeck/src/inherited.rs b/compiler/rustc_hir_typeck/src/inherited.rs index 16462be758f..efd0b8577cf 100644 --- a/compiler/rustc_hir_typeck/src/inherited.rs +++ b/compiler/rustc_hir_typeck/src/inherited.rs @@ -55,7 +55,7 @@ pub struct Inherited<'tcx> { pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, hir::HirId)>>, - pub(super) deferred_generator_interiors: + pub(super) deferred_coroutine_interiors: RefCell<Vec<(LocalDefId, hir::BodyId, Ty<'tcx>, hir::CoroutineKind)>>, /// Whenever we introduce an adjustment from `!` into a type variable, @@ -94,7 +94,7 @@ impl<'tcx> Inherited<'tcx> { deferred_cast_checks: RefCell::new(Vec::new()), deferred_transmute_checks: RefCell::new(Vec::new()), deferred_asm_checks: RefCell::new(Vec::new()), - deferred_generator_interiors: RefCell::new(Vec::new()), + deferred_coroutine_interiors: RefCell::new(Vec::new()), diverging_type_vars: RefCell::new(Default::default()), infer_var_info: RefCell::new(Default::default()), } diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 98778d6b98d..46dcc455558 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -255,11 +255,11 @@ fn typeck_with_fallback<'tcx>( fcx.check_casts(); fcx.select_obligations_where_possible(|_| {}); - // Closure and generator analysis may run after fallback + // Closure and coroutine analysis may run after fallback // because they don't constrain other type variables. fcx.closure_analyze(body); assert!(fcx.deferred_call_resolutions.borrow().is_empty()); - // Before the generator analysis, temporary scopes shall be marked to provide more + // Before the coroutine analysis, temporary scopes shall be marked to provide more // precise information on types to be captured. fcx.resolve_rvalue_scopes(def_id.to_def_id()); @@ -273,7 +273,7 @@ fn typeck_with_fallback<'tcx>( debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations()); // This must be the last thing before `report_ambiguity_errors`. - fcx.resolve_generator_interiors(def_id.to_def_id()); + fcx.resolve_coroutine_interiors(def_id.to_def_id()); debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations()); @@ -298,11 +298,11 @@ fn typeck_with_fallback<'tcx>( typeck_results } -/// When `check_fn` is invoked on a generator (i.e., a body that +/// When `check_fn` is invoked on a coroutine (i.e., a body that /// includes yield), it returns back some information about the yield /// points. struct CoroutineTypes<'tcx> { - /// Type of generator argument / values returned by `yield`. + /// Type of coroutine argument / values returned by `yield`. resume_ty: Ty<'tcx>, /// Type of value that is yielded. @@ -311,7 +311,7 @@ struct CoroutineTypes<'tcx> { /// Types that are captured (see `CoroutineInterior` for more). interior: Ty<'tcx>, - /// Indicates if the generator is movable or static (immovable). + /// Indicates if the coroutine is movable or static (immovable). movability: hir::Movability, } diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index a3a93141f42..75c70ec59fb 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -366,7 +366,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Note that we *always* infer a minimal kind, even if /// we don't always *use* that in the final result (i.e., sometimes /// we've taken the closure kind from the expectations instead, and - /// for generators we don't even implement the closure traits + /// for coroutines we don't even implement the closure traits /// really). /// /// If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 322859154bb..896aacc6993 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -63,7 +63,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { wbcx.visit_coercion_casts(); wbcx.visit_user_provided_tys(); wbcx.visit_user_provided_sigs(); - wbcx.visit_generator_interior(); + wbcx.visit_coroutine_interior(); wbcx.visit_offset_of_container_types(); wbcx.typeck_results.rvalue_scopes = @@ -540,16 +540,16 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { ); } - fn visit_generator_interior(&mut self) { + fn visit_coroutine_interior(&mut self) { let fcx_typeck_results = self.fcx.typeck_results.borrow(); assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); self.tcx().with_stable_hashing_context(move |ref hcx| { for (&expr_def_id, predicates) in - fcx_typeck_results.generator_interior_predicates.to_sorted(hcx, false).into_iter() + fcx_typeck_results.coroutine_interior_predicates.to_sorted(hcx, false).into_iter() { let predicates = self.resolve(predicates.clone(), &self.fcx.tcx.def_span(expr_def_id)); - self.typeck_results.generator_interior_predicates.insert(expr_def_id, predicates); + self.typeck_results.coroutine_interior_predicates.insert(expr_def_id, predicates); } }) } diff --git a/compiler/rustc_infer/messages.ftl b/compiler/rustc_infer/messages.ftl index b36fb6a4dba..2de87cbe631 100644 --- a/compiler/rustc_infer/messages.ftl +++ b/compiler/rustc_infer/messages.ftl @@ -181,19 +181,19 @@ infer_more_targeted = {$has_param_name -> infer_msl_introduces_static = introduces a `'static` lifetime requirement infer_msl_unmet_req = because this has an unmet lifetime requirement -infer_need_type_info_in_generator = - type inside {$generator_kind -> +infer_need_type_info_in_coroutine = + type inside {$coroutine_kind -> [async_block] `async` block [async_closure] `async` closure [async_fn] `async fn` body - *[generator] generator + *[coroutine] coroutine } must be known in this context infer_nothing = {""} infer_oc_cant_coerce = cannot coerce intrinsics to function pointers -infer_oc_closure_selfref = closure/generator type that references itself +infer_oc_closure_selfref = closure/coroutine type that references itself infer_oc_const_compat = const not compatible with trait infer_oc_fn_lang_correct_type = {$lang_item_name -> [panic_impl] `#[panic_handler]` @@ -284,7 +284,7 @@ infer_sbfrit_change_return_type = you could change the return type to be a boxed infer_source_kind_closure_return = try giving this closure an explicit return type -# generator_kind may need to be translated +# coroutine_kind may need to be translated infer_source_kind_fully_qualified = try using a fully qualified path to specify the expected types diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 60d48c62481..fdeaf7f6850 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -2821,7 +2821,7 @@ impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> { // say, also take a look at the error code, maybe we can // tailor to that. _ => match terr { - TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => Error0644, + TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_coroutine() => Error0644, TypeError::IntrinsicCast => Error0308, _ => Error0308, }, @@ -2868,7 +2868,7 @@ impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> { // say, also take a look at the error code, maybe we can // tailor to that. _ => match terr { - TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => { + TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_coroutine() => { ObligationCauseFailureCode::ClosureSelfref { span } } TypeError::IntrinsicCast => { @@ -2960,7 +2960,7 @@ impl TyCategory { Some((kind, def_id)) } ty::Coroutine(def_id, ..) => { - Some((Self::Coroutine(tcx.generator_kind(def_id).unwrap()), def_id)) + Some((Self::Coroutine(tcx.coroutine_kind(def_id).unwrap()), def_id)) } ty::Foreign(def_id) => Some((Self::Foreign, def_id)), _ => None, diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index 8809b967aee..7bc414ff522 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -868,7 +868,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { ) { // Opaque types can't be named by the user right now. // - // Both the generic arguments of closures and generators can + // Both the generic arguments of closures and coroutines can // also not be named. We may want to only look into the closure // signature in case it has no captures, as that can be represented // using `fn(T) -> R`. diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index ca620aafc5c..faea8bc98aa 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -325,7 +325,7 @@ impl<T> Trait<T> for X { } CyclicTy(ty) => { // Watch out for various cases of cyclic types and try to explain. - if ty.is_closure() || ty.is_generator() { + if ty.is_closure() || ty.is_coroutine() { diag.note( "closures cannot capture themselves or take themselves as argument;\n\ this error may be the result of a recent compiler bug-fix,\n\ diff --git a/compiler/rustc_infer/src/infer/opaque_types.rs b/compiler/rustc_infer/src/infer/opaque_types.rs index 3812cc9cd46..e1a14ed0faf 100644 --- a/compiler/rustc_infer/src/infer/opaque_types.rs +++ b/compiler/rustc_infer/src/infer/opaque_types.rs @@ -458,12 +458,12 @@ where // Skip lifetime parameters of the enclosing item(s) // Also skip the witness type, because that has no free regions. - for upvar in args.as_generator().upvar_tys() { + for upvar in args.as_coroutine().upvar_tys() { upvar.visit_with(self); } - args.as_generator().return_ty().visit_with(self); - args.as_generator().yield_ty().visit_with(self); - args.as_generator().resume_ty().visit_with(self); + args.as_coroutine().return_ty().visit_with(self); + args.as_coroutine().yield_ty().visit_with(self); + args.as_coroutine().resume_ty().visit_with(self); } ty::Alias(ty::Opaque, ty::AliasTy { def_id, ref args, .. }) => { diff --git a/compiler/rustc_infer/src/infer/outlives/components.rs b/compiler/rustc_infer/src/infer/outlives/components.rs index 9a8e7ab68f9..38819e8ad8a 100644 --- a/compiler/rustc_infer/src/infer/outlives/components.rs +++ b/compiler/rustc_infer/src/infer/outlives/components.rs @@ -104,10 +104,10 @@ fn compute_components<'tcx>( ty::Coroutine(_, ref args, _) => { // Same as the closure case - let tupled_ty = args.as_generator().tupled_upvars_ty(); + let tupled_ty = args.as_coroutine().tupled_upvars_ty(); compute_components(tcx, tupled_ty, out, visited); - // We ignore regions in the generator interior as we don't + // We ignore regions in the coroutine interior as we don't // want these to affect region inference } diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 2c8d32450be..7a7e9024bd8 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -800,8 +800,8 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> { tcx.hir().par_body_owners(|def_id| { if let rustc_hir::def::DefKind::Coroutine = tcx.def_kind(def_id) { - tcx.ensure().mir_generator_witnesses(def_id); - tcx.ensure().check_generator_obligations(def_id); + tcx.ensure().mir_coroutine_witnesses(def_id); + tcx.ensure().check_coroutine_obligations(def_id); } }); diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index 4c4d2933bf4..068f1372c0e 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -551,19 +551,19 @@ lint_unused_closure = lint_unused_comparisons = comparison is useless due to type limits +lint_unused_coroutine = + unused {$pre}{$count -> + [one] coroutine + *[other] coroutine + }{$post} that must be used + .note = coroutines are lazy and do nothing unless resumed + lint_unused_def = unused {$pre}`{$def}`{$post} that must be used .suggestion = use `let _ = ...` to ignore the resulting value lint_unused_delim = unnecessary {$delim} around {$item} .suggestion = remove these {$delim} -lint_unused_generator = - unused {$pre}{$count -> - [one] generator - *[other] generator - }{$post} that must be used - .note = generators are lazy and do nothing unless resumed - lint_unused_import_braces = braces around {$node} is unnecessary lint_unused_op = unused {$op} that must be used diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index ce52e95e0f1..756899e50a8 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -1700,7 +1700,7 @@ pub struct UnusedClosure<'a> { // FIXME(davidtwco): this isn't properly translatable because of the // pre/post strings #[derive(LintDiagnostic)] -#[diag(lint_unused_generator)] +#[diag(lint_unused_coroutine)] #[note] pub struct UnusedCoroutine<'a> { pub count: usize, diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index c757bc85021..6b31fb079e0 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -257,7 +257,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { Array(Box<Self>, u64), /// The root of the unused_closures lint. Closure(Span), - /// The root of the unused_generators lint. + /// The root of the unused_coroutines lint. Coroutine(Span), } @@ -352,7 +352,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { ty::Closure(..) => Some(MustUsePath::Closure(span)), ty::Coroutine(def_id, ..) => { // async fn should be treated as "implementor of `Future`" - let must_use = if cx.tcx.generator_is_async(def_id) { + let must_use = if cx.tcx.coroutine_is_async(def_id) { let def_id = cx.tcx.lang_items().future_trait()?; is_def_must_use(cx, def_id, span) .map(|inner| MustUsePath::Opaque(Box::new(inner))) diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs index ddeb39669dc..ec2517b581e 100644 --- a/compiler/rustc_metadata/src/lib.rs +++ b/compiler/rustc_metadata/src/lib.rs @@ -4,8 +4,9 @@ #![cfg_attr(not(bootstrap), allow(internal_features))] #![feature(decl_macro)] #![feature(extract_if)] -#![feature(generators)] -#![feature(iter_from_generator)] +#![cfg_attr(bootstrap, feature(generators))] +#![cfg_attr(not(bootstrap), feature(coroutines))] +#![feature(iter_from_coroutine)] #![feature(let_chains)] #![feature(proc_macro_internals)] #![feature(macro_metavar_expr)] diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index d6ceaa8a091..354023cea9e 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -1239,7 +1239,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { id: DefIndex, sess: &'a Session, ) -> impl Iterator<Item = ModChild> + 'a { - iter::from_generator(move || { + iter::from_coroutine(move || { if let Some(data) = &self.root.proc_macro_data { // If we are loading as a proc macro, we want to return // the view of this crate as a proc macro crate. diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 6b6c0d52742..595d816e949 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -221,7 +221,7 @@ provide! { tcx, def_id, other, cdata, optimized_mir => { table } mir_for_ctfe => { table } closure_saved_names_of_captured_variables => { table } - mir_generator_witnesses => { table } + mir_coroutine_witnesses => { table } promoted_mir => { table } def_span => { table } def_ident_span => { table } @@ -241,7 +241,7 @@ provide! { tcx, def_id, other, cdata, rendered_const => { table } asyncness => { table_direct } fn_arg_names => { table } - generator_kind => { table } + coroutine_kind => { table } trait_def => { table } deduced_param_attrs => { table } is_type_alias_impl_trait => { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index de17462130d..de436c16ca9 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1447,8 +1447,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } } if let DefKind::Coroutine = def_kind { - let data = self.tcx.generator_kind(def_id).unwrap(); - record!(self.tables.generator_kind[def_id] <- data); + let data = self.tcx.coroutine_kind(def_id).unwrap(); + record!(self.tables.coroutine_kind[def_id] <- data); } if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind { self.encode_info_for_adt(local_id); @@ -1630,9 +1630,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { <- tcx.closure_saved_names_of_captured_variables(def_id)); if let DefKind::Coroutine = self.tcx.def_kind(def_id) - && let Some(witnesses) = tcx.mir_generator_witnesses(def_id) + && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id) { - record!(self.tables.mir_generator_witnesses[def_id.to_def_id()] <- witnesses); + record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses); } } if encode_const { @@ -1657,9 +1657,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id)); if let DefKind::Coroutine = self.tcx.def_kind(def_id) - && let Some(witnesses) = tcx.mir_generator_witnesses(def_id) + && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id) { - record!(self.tables.mir_generator_witnesses[def_id.to_def_id()] <- witnesses); + record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses); } let instance = ty::InstanceDef::Item(def_id.to_def_id()); diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 1e0fcfa239d..9ae5c0af0b2 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -429,7 +429,7 @@ define_tables! { mir_for_ctfe: Table<DefIndex, LazyValue<mir::Body<'static>>>, cross_crate_inlinable: Table<DefIndex, bool>, closure_saved_names_of_captured_variables: Table<DefIndex, LazyValue<IndexVec<FieldIdx, Symbol>>>, - mir_generator_witnesses: Table<DefIndex, LazyValue<mir::CoroutineLayout<'static>>>, + mir_coroutine_witnesses: Table<DefIndex, LazyValue<mir::CoroutineLayout<'static>>>, promoted_mir: Table<DefIndex, LazyValue<IndexVec<mir::Promoted, mir::Body<'static>>>>, thir_abstract_const: Table<DefIndex, LazyValue<ty::EarlyBinder<ty::Const<'static>>>>, impl_parent: Table<DefIndex, RawDefId>, @@ -442,7 +442,7 @@ define_tables! { rendered_const: Table<DefIndex, LazyValue<String>>, asyncness: Table<DefIndex, ty::Asyncness>, fn_arg_names: Table<DefIndex, LazyArray<Ident>>, - generator_kind: Table<DefIndex, LazyValue<hir::CoroutineKind>>, + coroutine_kind: Table<DefIndex, LazyValue<hir::CoroutineKind>>, trait_def: Table<DefIndex, LazyValue<ty::TraitDef>>, trait_item_def_id: Table<DefIndex, RawDefId>, expn_that_defined: Table<DefIndex, LazyValue<ExpnId>>, diff --git a/compiler/rustc_middle/messages.ftl b/compiler/rustc_middle/messages.ftl index 82162fd8571..37ff5bcf1e2 100644 --- a/compiler/rustc_middle/messages.ftl +++ b/compiler/rustc_middle/messages.ftl @@ -5,12 +5,12 @@ middle_assert_async_resume_after_panic = `async fn` resumed after panicking middle_assert_async_resume_after_return = `async fn` resumed after completion -middle_assert_divide_by_zero = - attempt to divide `{$val}` by zero +middle_assert_coroutine_resume_after_panic = coroutine resumed after panicking -middle_assert_generator_resume_after_panic = generator resumed after panicking +middle_assert_coroutine_resume_after_return = coroutine resumed after completion -middle_assert_generator_resume_after_return = generator resumed after completion +middle_assert_divide_by_zero = + attempt to divide `{$val}` by zero middle_assert_misaligned_ptr_deref = misaligned pointer dereference: address must be a multiple of {$required} but is {$found} diff --git a/compiler/rustc_middle/src/hir/nested_filter.rs b/compiler/rustc_middle/src/hir/nested_filter.rs index 6896837aa91..adbe81bb22c 100644 --- a/compiler/rustc_middle/src/hir/nested_filter.rs +++ b/compiler/rustc_middle/src/hir/nested_filter.rs @@ -4,7 +4,7 @@ use rustc_hir::intravisit::nested_filter::NestedFilter; /// that are inside of an item-like. /// /// Notably, possible occurrences of bodies in non-item-like things -/// include: closures/generators, inline `const {}` blocks, and +/// include: closures/coroutines, inline `const {}` blocks, and /// constant arguments of types, e.g. in `let _: [(); /* HERE */];`. /// /// **This is the most common choice.** A very common pattern is diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index dee18dc1162..448a3029ae9 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -32,11 +32,12 @@ #![feature(core_intrinsics)] #![feature(discriminant_kind)] #![feature(exhaustive_patterns)] -#![feature(generators)] +#![cfg_attr(bootstrap, feature(generators))] +#![cfg_attr(not(bootstrap), feature(coroutines))] #![feature(get_mut_unchecked)] #![feature(if_let_guard)] #![feature(inline_const)] -#![feature(iter_from_generator)] +#![feature(iter_from_coroutine)] #![feature(negative_impls)] #![feature(never_type)] #![feature(extern_types)] diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index c50c5e6f701..56fed05c63f 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -308,7 +308,7 @@ pub struct ScopeTree { /// The number of visit_expr and visit_pat calls done in the body. /// Used to sanity check visit_expr/visit_pat call count when - /// calculating generator interiors. + /// calculating coroutine interiors. pub body_expr_count: FxHashMap<hir::BodyId, usize>, } @@ -413,7 +413,7 @@ impl ScopeTree { /// Gives the number of expressions visited in a body. /// Used to sanity check visit_expr call count when - /// calculating generator interiors. + /// calculating coroutine interiors. pub fn body_expr_count(&self, body_id: hir::BodyId) -> Option<usize> { self.body_expr_count.get(&body_id).copied() } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 01846ccf883..a85af7c3fb5 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -247,18 +247,18 @@ impl<'tcx> MirSource<'tcx> { #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)] pub struct CoroutineInfo<'tcx> { - /// The yield type of the function, if it is a generator. + /// The yield type of the function, if it is a coroutine. pub yield_ty: Option<Ty<'tcx>>, /// Coroutine drop glue. - pub generator_drop: Option<Body<'tcx>>, + pub coroutine_drop: Option<Body<'tcx>>, - /// The layout of a generator. Produced by the state transformation. - pub generator_layout: Option<CoroutineLayout<'tcx>>, + /// The layout of a coroutine. Produced by the state transformation. + pub coroutine_layout: Option<CoroutineLayout<'tcx>>, - /// If this is a generator then record the type of source expression that caused this generator + /// If this is a coroutine then record the type of source expression that caused this coroutine /// to be created. - pub generator_kind: CoroutineKind, + pub coroutine_kind: CoroutineKind, } /// The lowered representation of a single function. @@ -284,7 +284,7 @@ pub struct Body<'tcx> { /// and used for debuginfo. Indexed by a `SourceScope`. pub source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>, - pub generator: Option<Box<CoroutineInfo<'tcx>>>, + pub coroutine: Option<Box<CoroutineInfo<'tcx>>>, /// Declarations of locals. /// @@ -365,7 +365,7 @@ impl<'tcx> Body<'tcx> { arg_count: usize, var_debug_info: Vec<VarDebugInfo<'tcx>>, span: Span, - generator_kind: Option<CoroutineKind>, + coroutine_kind: Option<CoroutineKind>, tainted_by_errors: Option<ErrorGuaranteed>, ) -> Self { // We need `arg_count` locals, and one for the return place. @@ -382,12 +382,12 @@ impl<'tcx> Body<'tcx> { source, basic_blocks: BasicBlocks::new(basic_blocks), source_scopes, - generator: generator_kind.map(|generator_kind| { + coroutine: coroutine_kind.map(|coroutine_kind| { Box::new(CoroutineInfo { yield_ty: None, - generator_drop: None, - generator_layout: None, - generator_kind, + coroutine_drop: None, + coroutine_layout: None, + coroutine_kind, }) }), local_decls, @@ -418,7 +418,7 @@ impl<'tcx> Body<'tcx> { source: MirSource::item(CRATE_DEF_ID.to_def_id()), basic_blocks: BasicBlocks::new(basic_blocks), source_scopes: IndexVec::new(), - generator: None, + coroutine: None, local_decls: IndexVec::new(), user_type_annotations: IndexVec::new(), arg_count: 0, @@ -548,22 +548,22 @@ impl<'tcx> Body<'tcx> { #[inline] pub fn yield_ty(&self) -> Option<Ty<'tcx>> { - self.generator.as_ref().and_then(|generator| generator.yield_ty) + self.coroutine.as_ref().and_then(|coroutine| coroutine.yield_ty) } #[inline] - pub fn generator_layout(&self) -> Option<&CoroutineLayout<'tcx>> { - self.generator.as_ref().and_then(|generator| generator.generator_layout.as_ref()) + pub fn coroutine_layout(&self) -> Option<&CoroutineLayout<'tcx>> { + self.coroutine.as_ref().and_then(|coroutine| coroutine.coroutine_layout.as_ref()) } #[inline] - pub fn generator_drop(&self) -> Option<&Body<'tcx>> { - self.generator.as_ref().and_then(|generator| generator.generator_drop.as_ref()) + pub fn coroutine_drop(&self) -> Option<&Body<'tcx>> { + self.coroutine.as_ref().and_then(|coroutine| coroutine.coroutine_drop.as_ref()) } #[inline] - pub fn generator_kind(&self) -> Option<CoroutineKind> { - self.generator.as_ref().map(|generator| generator.generator_kind) + pub fn coroutine_kind(&self) -> Option<CoroutineKind> { + self.coroutine.as_ref().map(|coroutine| coroutine.coroutine_kind) } #[inline] diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 9ec0401b4fb..dee25df53bd 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -130,8 +130,8 @@ fn dump_matched_mir_node<'tcx, F>( Some(promoted) => write!(file, "::{promoted:?}`")?, } writeln!(file, " {disambiguator} {pass_name}")?; - if let Some(ref layout) = body.generator_layout() { - writeln!(file, "/* generator_layout = {layout:#?} */")?; + if let Some(ref layout) = body.coroutine_layout() { + writeln!(file, "/* coroutine_layout = {layout:#?} */")?; } writeln!(file)?; extra_data(PassWhere::BeforeCFG, &mut file)?; @@ -782,7 +782,7 @@ impl<'tcx> TerminatorKind<'tcx> { Goto { .. } => write!(fmt, "goto"), SwitchInt { discr, .. } => write!(fmt, "switchInt({discr:?})"), Return => write!(fmt, "return"), - CoroutineDrop => write!(fmt, "generator_drop"), + CoroutineDrop => write!(fmt, "coroutine_drop"), UnwindResume => write!(fmt, "resume"), UnwindTerminate(reason) => { write!(fmt, "abort({})", reason.as_short_str()) @@ -1047,7 +1047,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { }), AggregateKind::Coroutine(def_id, _, _) => ty::tls::with(|tcx| { - let name = format!("{{generator@{:?}}}", tcx.def_span(def_id)); + let name = format!("{{coroutine@{:?}}}", tcx.def_span(def_id)); let mut struct_fmt = fmt.debug_struct(&name); // FIXME(project-rfc-2229#48): This should be a list of capture names/places @@ -1302,7 +1302,7 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { } AggregateKind::Coroutine(def_id, args, movability) => { - self.push("generator"); + self.push("coroutine"); self.push(&format!("+ def_id: {def_id:?}")); self.push(&format!("+ args: {args:#?}")); self.push(&format!("+ movability: {movability:?}")); diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index 97588ae77c2..0540eb0efd6 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -145,10 +145,10 @@ pub struct CoroutineSavedTy<'tcx> { pub ignore_for_traits: bool, } -/// The layout of generator state. +/// The layout of coroutine state. #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)] pub struct CoroutineLayout<'tcx> { - /// The type of every local stored inside the generator. + /// The type of every local stored inside the coroutine. pub field_tys: IndexVec<CoroutineSavedLocal, CoroutineSavedTy<'tcx>>, /// The name for debuginfo. @@ -185,7 +185,7 @@ impl Debug for CoroutineLayout<'_> { } } - /// Prints the generator variant name. + /// Prints the coroutine variant name. struct GenVariantPrinter(VariantIdx); impl From<VariantIdx> for GenVariantPrinter { fn from(idx: VariantIdx) -> Self { @@ -259,7 +259,7 @@ pub struct ConstQualifs { /// /// The requirements are listed as being between various `RegionVid`. The 0th /// region refers to `'static`; subsequent region vids refer to the free -/// regions that appear in the closure (or generator's) type, in order of +/// regions that appear in the closure (or coroutine's) type, in order of /// appearance. (This numbering is actually defined by the `UniversalRegions` /// struct in the NLL region checker. See for example /// `UniversalRegions::closure_mapping`.) Note the free regions in the diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 23e323a4820..b89c7bc512e 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -83,9 +83,9 @@ pub enum MirPhase { /// don't document this here. Runtime MIR has most retags explicit (though implicit retags /// can still occur at `Rvalue::{Ref,AddrOf}`). /// - Coroutine bodies: In analysis MIR, locals may actually be behind a pointer that user code has - /// access to. This occurs in generator bodies. Such locals do not behave like other locals, + /// access to. This occurs in coroutine bodies. Such locals do not behave like other locals, /// because they eg may be aliased in surprising ways. Runtime MIR has no such special locals - - /// all generator bodies are lowered and so all places that look like locals really are locals. + /// all coroutine bodies are lowered and so all places that look like locals really are locals. /// /// Also note that the lint pass which reports eg `200_u8 + 200_u8` as an error is run as a part /// of analysis to runtime MIR lowering. To ensure lints are reported reliably, this means that @@ -292,7 +292,7 @@ pub enum StatementKind<'tcx> { /// Write the discriminant for a variant to the enum Place. /// - /// This is permitted for both generators and ADTs. This does not necessarily write to the + /// This is permitted for both coroutines and ADTs. This does not necessarily write to the /// entire place; instead, it writes to the minimum set of bytes as required by the layout for /// the type. SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx }, @@ -626,7 +626,7 @@ pub enum TerminatorKind<'tcx> { /// `dest = move _0`. It might additionally do other things, like have side-effects in the /// aliasing model. /// - /// If the body is a generator body, this has slightly different semantics; it instead causes a + /// If the body is a coroutine body, this has slightly different semantics; it instead causes a /// `CoroutineState::Returned(_0)` to be created (as if by an `Aggregate` rvalue) and assigned /// to the return place. Return, @@ -709,14 +709,14 @@ pub enum TerminatorKind<'tcx> { /// Marks a suspend point. /// - /// Like `Return` terminators in generator bodies, this computes `value` and then a + /// Like `Return` terminators in coroutine bodies, this computes `value` and then a /// `CoroutineState::Yielded(value)` as if by `Aggregate` rvalue. That value is then assigned to /// the return place of the function calling this one, and execution continues in the calling /// function. When next invoked with the same first argument, execution of this function /// continues at the `resume` basic block, with the second argument written to the `resume_arg` - /// place. If the generator is dropped before then, the `drop` basic block is invoked. + /// place. If the coroutine is dropped before then, the `drop` basic block is invoked. /// - /// Not permitted in bodies that are not generator bodies, or after generator lowering. + /// Not permitted in bodies that are not coroutine bodies, or after coroutine lowering. /// /// **Needs clarification**: What about the evaluation order of the `resume_arg` and `value`? Yield { @@ -726,16 +726,16 @@ pub enum TerminatorKind<'tcx> { resume: BasicBlock, /// The place to store the resume argument in. resume_arg: Place<'tcx>, - /// Cleanup to be done if the generator is dropped at this suspend point. + /// Cleanup to be done if the coroutine is dropped at this suspend point. drop: Option<BasicBlock>, }, - /// Indicates the end of dropping a generator. + /// Indicates the end of dropping a coroutine. /// - /// Semantically just a `return` (from the generators drop glue). Only permitted in the same situations + /// Semantically just a `return` (from the coroutines drop glue). Only permitted in the same situations /// as `yield`. /// - /// **Needs clarification**: Is that even correct? The generator drop code is always confusing + /// **Needs clarification**: Is that even correct? The coroutine drop code is always confusing /// to me, because it's not even really in the current body. /// /// **Needs clarification**: Are there type system constraints on these terminators? Should @@ -961,8 +961,8 @@ pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>; /// was unsized and so had metadata associated with it, then the metadata is retained if the /// field is unsized and thrown out if it is sized. /// -/// These projections are only legal for tuples, ADTs, closures, and generators. If the ADT or -/// generator has more than one variant, the parent place's variant index must be set, indicating +/// These projections are only legal for tuples, ADTs, closures, and coroutines. If the ADT or +/// coroutine has more than one variant, the parent place's variant index must be set, indicating /// which variant is being used. If it has just one variant, the variant index may or may not be /// included - the single possible variant is inferred if it is not included. /// - [`OpaqueCast`](ProjectionElem::OpaqueCast): This projection changes the place's type to the @@ -1068,7 +1068,7 @@ pub enum ProjectionElem<V, T> { from_end: bool, }, - /// "Downcast" to a variant of an enum or a generator. + /// "Downcast" to a variant of an enum or a coroutine. /// /// The included Symbol is the name of the variant, used for printing MIR. Downcast(Option<Symbol>, VariantIdx), @@ -1279,7 +1279,7 @@ pub enum Rvalue<'tcx> { /// has a destructor. /// /// Disallowed after deaggregation for all aggregate kinds except `Array` and `Coroutine`. After - /// generator lowering, `Coroutine` aggregate kinds are disallowed too. + /// coroutine lowering, `Coroutine` aggregate kinds are disallowed too. Aggregate(Box<AggregateKind<'tcx>>, IndexVec<FieldIdx, Operand<'tcx>>), /// Transmutes a `*mut u8` into shallow-initialized `Box<T>`. diff --git a/compiler/rustc_middle/src/mir/tcx.rs b/compiler/rustc_middle/src/mir/tcx.rs index 27f0715dffb..931ee7fd05e 100644 --- a/compiler/rustc_middle/src/mir/tcx.rs +++ b/compiler/rustc_middle/src/mir/tcx.rs @@ -11,7 +11,7 @@ use rustc_target::abi::{FieldIdx, VariantIdx}; #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)] pub struct PlaceTy<'tcx> { pub ty: Ty<'tcx>, - /// Downcast to a particular variant of an enum or a generator, if included. + /// Downcast to a particular variant of an enum or a coroutine, if included. pub variant_index: Option<VariantIdx>, } @@ -206,7 +206,7 @@ impl<'tcx> Rvalue<'tcx> { AggregateKind::Adt(did, _, args, _, _) => tcx.type_of(did).instantiate(tcx, args), AggregateKind::Closure(did, args) => Ty::new_closure(tcx, did, args), AggregateKind::Coroutine(did, args, movability) => { - Ty::new_generator(tcx, did, args, movability) + Ty::new_coroutine(tcx, did, args, movability) } }, Rvalue::ShallowInitBox(_, ty) => Ty::new_box(tcx, ty), diff --git a/compiler/rustc_middle/src/mir/terminator.rs b/compiler/rustc_middle/src/mir/terminator.rs index 86515b14fed..9a85b671d9d 100644 --- a/compiler/rustc_middle/src/mir/terminator.rs +++ b/compiler/rustc_middle/src/mir/terminator.rs @@ -139,9 +139,9 @@ impl<O> AssertKind<O> { Overflow(op, _, _) => bug!("{:?} cannot overflow", op), DivisionByZero(_) => "attempt to divide by zero", RemainderByZero(_) => "attempt to calculate the remainder with a divisor of zero", - ResumedAfterReturn(CoroutineKind::Gen) => "generator resumed after completion", + ResumedAfterReturn(CoroutineKind::Gen) => "coroutine resumed after completion", ResumedAfterReturn(CoroutineKind::Async(_)) => "`async fn` resumed after completion", - ResumedAfterPanic(CoroutineKind::Gen) => "generator resumed after panicking", + ResumedAfterPanic(CoroutineKind::Gen) => "coroutine resumed after panicking", ResumedAfterPanic(CoroutineKind::Async(_)) => "`async fn` resumed after panicking", BoundsCheck { .. } | MisalignedPointerDereference { .. } => { bug!("Unexpected AssertKind") @@ -229,9 +229,9 @@ impl<O> AssertKind<O> { DivisionByZero(_) => middle_assert_divide_by_zero, RemainderByZero(_) => middle_assert_remainder_by_zero, ResumedAfterReturn(CoroutineKind::Async(_)) => middle_assert_async_resume_after_return, - ResumedAfterReturn(CoroutineKind::Gen) => middle_assert_generator_resume_after_return, + ResumedAfterReturn(CoroutineKind::Gen) => middle_assert_coroutine_resume_after_return, ResumedAfterPanic(CoroutineKind::Async(_)) => middle_assert_async_resume_after_panic, - ResumedAfterPanic(CoroutineKind::Gen) => middle_assert_generator_resume_after_panic, + ResumedAfterPanic(CoroutineKind::Gen) => middle_assert_coroutine_resume_after_panic, MisalignedPointerDereference { .. } => middle_assert_misaligned_ptr_deref, } diff --git a/compiler/rustc_middle/src/mir/visit.rs b/compiler/rustc_middle/src/mir/visit.rs index 805d368397b..0f0ca3a1420 100644 --- a/compiler/rustc_middle/src/mir/visit.rs +++ b/compiler/rustc_middle/src/mir/visit.rs @@ -737,10 +737,10 @@ macro_rules! make_mir_visitor { } AggregateKind::Coroutine( _, - generator_args, + coroutine_args, _movability, ) => { - self.visit_args(generator_args, location); + self.visit_args(coroutine_args, location); } } @@ -992,7 +992,7 @@ macro_rules! extra_body_methods { macro_rules! super_body { ($self:ident, $body:ident, $($mutability:ident, $invalidate:tt)?) => { let span = $body.span; - if let Some(gen) = &$($mutability)? $body.generator { + if let Some(gen) = &$($mutability)? $body.coroutine { if let Some(yield_ty) = $(& $mutability)? gen.yield_ty { $self.visit_ty( yield_ty, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 3c1e67d1846..b5f873c9257 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -541,28 +541,28 @@ rustc_queries! { } } - /// Returns names of captured upvars for closures and generators. + /// Returns names of captured upvars for closures and coroutines. /// /// Here are some examples: /// - `name__field1__field2` when the upvar is captured by value. /// - `_ref__name__field` when the upvar is captured by reference. /// - /// For generators this only contains upvars that are shared by all states. + /// For coroutines this only contains upvars that are shared by all states. query closure_saved_names_of_captured_variables(def_id: DefId) -> &'tcx IndexVec<abi::FieldIdx, Symbol> { arena_cache desc { |tcx| "computing debuginfo for closure `{}`", tcx.def_path_str(def_id) } separate_provide_extern } - query mir_generator_witnesses(key: DefId) -> &'tcx Option<mir::CoroutineLayout<'tcx>> { + query mir_coroutine_witnesses(key: DefId) -> &'tcx Option<mir::CoroutineLayout<'tcx>> { arena_cache - desc { |tcx| "generator witness types for `{}`", tcx.def_path_str(key) } + desc { |tcx| "coroutine witness types for `{}`", tcx.def_path_str(key) } cache_on_disk_if { key.is_local() } separate_provide_extern } - query check_generator_obligations(key: LocalDefId) { - desc { |tcx| "verify auto trait bounds for generator interior type `{}`", tcx.def_path_str(key) } + query check_coroutine_obligations(key: LocalDefId) { + desc { |tcx| "verify auto trait bounds for coroutine interior type `{}`", tcx.def_path_str(key) } } /// MIR after our optimization passes have run. This is MIR that is ready @@ -743,9 +743,9 @@ rustc_queries! { desc { |tcx| "checking if item is promotable: `{}`", tcx.def_path_str(key) } } - /// Returns `Some(generator_kind)` if the node pointed to by `def_id` is a generator. - query generator_kind(def_id: DefId) -> Option<hir::CoroutineKind> { - desc { |tcx| "looking up generator kind of `{}`", tcx.def_path_str(def_id) } + /// Returns `Some(coroutine_kind)` if the node pointed to by `def_id` is a coroutine. + query coroutine_kind(def_id: DefId) -> Option<hir::CoroutineKind> { + desc { |tcx| "looking up coroutine kind of `{}`", tcx.def_path_str(def_id) } separate_provide_extern } diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 67804998a32..20e3349073d 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -382,9 +382,9 @@ pub enum ExprKind<'tcx> { VarRef { id: LocalVarId, }, - /// Used to represent upvars mentioned in a closure/generator + /// Used to represent upvars mentioned in a closure/coroutine UpvarRef { - /// DefId of the closure/generator + /// DefId of the closure/coroutine closure_def_id: DefId, /// HirId of the root variable diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 43803dc406b..9397e98343e 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -301,7 +301,7 @@ pub enum ObligationCauseCode<'tcx> { InlineAsmSized, /// Captured closure type must be `Sized`. SizedClosureCapture(LocalDefId), - /// Types live across generator yields must be `Sized`. + /// Types live across coroutine yields must be `Sized`. SizedCoroutineInterior(LocalDefId), /// `[expr; N]` requires `type_of(expr): Copy`. RepeatElementCopy { diff --git a/compiler/rustc_middle/src/traits/select.rs b/compiler/rustc_middle/src/traits/select.rs index d3995c91714..bc6856bc900 100644 --- a/compiler/rustc_middle/src/traits/select.rs +++ b/compiler/rustc_middle/src/traits/select.rs @@ -137,10 +137,10 @@ pub enum SelectionCandidate<'tcx> { }, /// Implementation of a `Coroutine` trait by one of the anonymous types - /// generated for a generator. + /// generated for a coroutine. CoroutineCandidate, - /// Implementation of a `Future` trait by one of the generator types + /// Implementation of a `Future` trait by one of the coroutine types /// generated for an async construct. FutureCandidate, diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 69cfb99186b..561699d3170 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -761,9 +761,9 @@ impl<'tcx> TyCtxt<'tcx> { self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did) } - /// Returns `true` if the node pointed to by `def_id` is a generator for an async construct. - pub fn generator_is_async(self, def_id: DefId) -> bool { - matches!(self.generator_kind(def_id), Some(hir::CoroutineKind::Async(_))) + /// Returns `true` if the node pointed to by `def_id` is a coroutine for an async construct. + pub fn coroutine_is_async(self, def_id: DefId) -> bool { + matches!(self.coroutine_kind(def_id), Some(hir::CoroutineKind::Async(_))) } pub fn stability(self) -> &'tcx stability::Index { @@ -951,7 +951,7 @@ impl<'tcx> TyCtxt<'tcx> { self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE); let definitions = &self.untracked.definitions; - std::iter::from_generator(|| { + std::iter::from_coroutine(|| { let mut i = 0; // Recompute the number of definitions each time, because our caller may be creating diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 8a21d1d2e31..8b4375f0270 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -241,8 +241,8 @@ impl<'tcx> Ty<'tcx> { } ty::Dynamic(..) => "trait object".into(), ty::Closure(..) => "closure".into(), - ty::Coroutine(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(), - ty::CoroutineWitness(..) => "generator witness".into(), + ty::Coroutine(def_id, ..) => tcx.coroutine_kind(def_id).unwrap().descr().into(), + ty::CoroutineWitness(..) => "coroutine witness".into(), ty::Infer(ty::TyVar(_)) => "inferred type".into(), ty::Infer(ty::IntVar(_)) => "integer".into(), ty::Infer(ty::FloatVar(_)) => "floating-point number".into(), @@ -299,8 +299,8 @@ impl<'tcx> Ty<'tcx> { ty::FnPtr(_) => "fn pointer".into(), ty::Dynamic(..) => "trait object".into(), ty::Closure(..) => "closure".into(), - ty::Coroutine(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(), - ty::CoroutineWitness(..) => "generator witness".into(), + ty::Coroutine(def_id, ..) => tcx.coroutine_kind(def_id).unwrap().descr().into(), + ty::CoroutineWitness(..) => "coroutine witness".into(), ty::Tuple(..) => "tuple".into(), ty::Placeholder(..) => "higher-ranked type".into(), ty::Bound(..) => "bound type variable".into(), diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index 93a4ff0a279..d75315b7ac9 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -112,7 +112,7 @@ impl FlagComputation { } ty::Coroutine(_, args, _) => { - let args = args.as_generator(); + let args = args.as_coroutine(); let should_remove_further_specializable = !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); self.add_args(args.parent_args()); diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 35478f2008c..41a1bf04e5f 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -266,11 +266,11 @@ impl<'tcx> GenericArgs<'tcx> { ClosureArgs { args: self } } - /// Interpret these generic args as the args of a generator type. + /// Interpret these generic args as the args of a coroutine type. /// Coroutine args have a particular structure controlled by the - /// compiler that encodes information like the signature and generator kind; + /// compiler that encodes information like the signature and coroutine kind; /// see `ty::CoroutineArgs` struct for more comments. - pub fn as_generator(&'tcx self) -> CoroutineArgs<'tcx> { + pub fn as_coroutine(&'tcx self) -> CoroutineArgs<'tcx> { CoroutineArgs { args: self } } diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index d4a0cc40ac6..a7d6e97c941 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -36,7 +36,7 @@ pub enum InstanceDef<'tcx> { /// This includes: /// - `fn` items /// - closures - /// - generators + /// - coroutines Item(DefId), /// An intrinsic `fn` item (with `"rust-intrinsic"` or `"platform-intrinsic"` ABI). @@ -653,15 +653,15 @@ fn polymorphize<'tcx>( let unused = tcx.unused_generic_params(instance); debug!("polymorphize: unused={:?}", unused); - // If this is a closure or generator then we need to handle the case where another closure + // If this is a closure or coroutine then we need to handle the case where another closure // from the function is captured as an upvar and hasn't been polymorphized. In this case, // the unpolymorphized upvar closure would result in a polymorphized closure producing // multiple mono items (and eventually symbol clashes). let def_id = instance.def_id(); let upvars_ty = if tcx.is_closure(def_id) { Some(args.as_closure().tupled_upvars_ty()) - } else if tcx.type_of(def_id).skip_binder().is_generator() { - Some(args.as_generator().tupled_upvars_ty()) + } else if tcx.type_of(def_id).skip_binder().is_coroutine() { + Some(args.as_coroutine().tupled_upvars_ty()) } else { None }; @@ -695,7 +695,7 @@ fn polymorphize<'tcx>( if args == polymorphized_args { ty } else { - Ty::new_generator(self.tcx, def_id, polymorphized_args, movability) + Ty::new_coroutine(self.tcx, def_id, polymorphized_args, movability) } } _ => ty.super_fold_with(self), @@ -715,7 +715,7 @@ fn polymorphize<'tcx>( upvars_ty == Some(args[param.index as usize].expect_ty()) => { // ..then double-check that polymorphization marked it used.. debug_assert!(!is_unused); - // ..and polymorphize any closures/generators captured as upvars. + // ..and polymorphize any closures/coroutines captured as upvars. let upvars_ty = upvars_ty.unwrap(); let polymorphized_upvars_ty = upvars_ty.fold_with( &mut PolymorphizationFolder { tcx }); diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 077c32b4274..4223e503f5e 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -898,7 +898,7 @@ where ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element), ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8), - // Tuples, generators and closures. + // Tuples, coroutines and closures. ty::Closure(_, ref args) => field_ty_or_layout( TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this }, cx, @@ -907,7 +907,7 @@ where ty::Coroutine(def_id, ref args, _) => match this.variants { Variants::Single { index } => TyMaybeWithLayout::Ty( - args.as_generator() + args.as_coroutine() .state_tys(def_id, tcx) .nth(index.as_usize()) .unwrap() @@ -918,7 +918,7 @@ where if i == tag_field { return TyMaybeWithLayout::TyAndLayout(tag_layout(tag)); } - TyMaybeWithLayout::Ty(args.as_generator().prefix_tys()[i]) + TyMaybeWithLayout::Ty(args.as_coroutine().prefix_tys()[i]) } }, diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index be0e41d89d3..9b0ceb23e3e 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -2421,10 +2421,10 @@ impl<'tcx> TyCtxt<'tcx> { self.def_kind(trait_def_id) == DefKind::TraitAlias } - /// Returns layout of a generator. Layout might be unavailable if the - /// generator is tainted by errors. - pub fn generator_layout(self, def_id: DefId) -> Option<&'tcx CoroutineLayout<'tcx>> { - self.optimized_mir(def_id).generator_layout() + /// Returns layout of a coroutine. Layout might be unavailable if the + /// coroutine is tainted by errors. + pub fn coroutine_layout(self, def_id: DefId) -> Option<&'tcx CoroutineLayout<'tcx>> { + self.optimized_mir(def_id).coroutine_layout() } /// Given the `DefId` of an impl, returns the `DefId` of the trait it implements. diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index 2f62bd3ca7a..8d895732dff 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -154,12 +154,12 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> { ty::Coroutine(def_id, args, movability) => { let args = self.fold_closure_args(def_id, args); - Ty::new_generator(self.tcx, def_id, args, movability) + Ty::new_coroutine(self.tcx, def_id, args, movability) } ty::CoroutineWitness(def_id, args) => { let args = self.fold_closure_args(def_id, args); - Ty::new_generator_witness(self.tcx, def_id, args) + Ty::new_coroutine_witness(self.tcx, def_id, args) } ty::Param(param) => { diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 0b5a04c9ec6..1836f3c1a4b 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -786,9 +786,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::Str => p!("str"), ty::Coroutine(did, args, movability) => { p!(write("{{")); - let generator_kind = self.tcx().generator_kind(did).unwrap(); + let coroutine_kind = self.tcx().coroutine_kind(did).unwrap(); let should_print_movability = - self.should_print_verbose() || generator_kind == hir::CoroutineKind::Gen; + self.should_print_verbose() || coroutine_kind == hir::CoroutineKind::Gen; if should_print_movability { match movability { @@ -798,7 +798,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } if !self.should_print_verbose() { - p!(write("{}", generator_kind)); + p!(write("{}", coroutine_kind)); // FIXME(eddyb) should use `def_span`. if let Some(did) = did.as_local() { let span = self.tcx().def_span(did); @@ -814,15 +814,15 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } else { p!(print_def_path(did, args)); p!(" upvar_tys=("); - if !args.as_generator().is_valid() { + if !args.as_coroutine().is_valid() { p!("unavailable"); } else { - self = self.comma_sep(args.as_generator().upvar_tys().iter())?; + self = self.comma_sep(args.as_coroutine().upvar_tys().iter())?; } p!(")"); - if args.as_generator().is_valid() { - p!(" ", print(args.as_generator().witness())); + if args.as_coroutine().is_valid() { + p!(" ", print(args.as_coroutine().witness())); } } @@ -831,7 +831,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::CoroutineWitness(did, args) => { p!(write("{{")); if !self.tcx().sess.verbose() { - p!("generator witness"); + p!("coroutine witness"); // FIXME(eddyb) should use `def_span`. if let Some(did) = did.as_local() { let span = self.tcx().def_span(did); @@ -1048,8 +1048,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } for (assoc_item_def_id, term) in assoc_items { - // Skip printing `<{generator@} as Coroutine<_>>::Return` from async blocks, - // unless we can find out what generator return type it comes from. + // Skip printing `<{coroutine@} as Coroutine<_>>::Return` from async blocks, + // unless we can find out what coroutine return type it comes from. let term = if let Some(ty) = term.skip_binder().ty() && let ty::Alias(ty::Projection, proj) = ty.kind() && let Some(assoc) = tcx.opt_associated_item(proj.def_id) @@ -1057,7 +1057,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { && assoc.name == rustc_span::sym::Return { if let ty::Coroutine(_, args, _) = args.type_at(0).kind() { - let return_ty = args.as_generator().return_ty(); + let return_ty = args.as_coroutine().return_ty(); if !return_ty.is_ty_var() { return_ty.into() } else { diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index af6127f0dbb..27e9be37fbf 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -461,20 +461,20 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>( if a_id == b_id => { // All Coroutine types with the same id represent - // the (anonymous) type of the same generator expression. So + // the (anonymous) type of the same coroutine expression. So // all of their regions should be equated. let args = relate_args_invariantly(relation, a_args, b_args)?; - Ok(Ty::new_generator(tcx, a_id, args, movability)) + Ok(Ty::new_coroutine(tcx, a_id, args, movability)) } (&ty::CoroutineWitness(a_id, a_args), &ty::CoroutineWitness(b_id, b_args)) if a_id == b_id => { // All CoroutineWitness types with the same id represent - // the (anonymous) type of the same generator expression. So + // the (anonymous) type of the same coroutine expression. So // all of their regions should be equated. let args = relate_args_invariantly(relation, a_args, b_args)?; - Ok(Ty::new_generator_witness(tcx, a_id, args)) + Ok(Ty::new_coroutine_witness(tcx, a_id, args)) } (&ty::Closure(a_id, a_args), &ty::Closure(b_id, b_args)) if a_id == b_id => { diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 7af2996d3a3..46aa5d950cb 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -221,14 +221,14 @@ impl<'tcx> Article for TyKind<'tcx> { /// type parameters is similar, but `CK` and `CS` are replaced by the /// following type parameters: /// -/// * `GS`: The generator's "resume type", which is the type of the +/// * `GS`: The coroutine's "resume type", which is the type of the /// argument passed to `resume`, and the type of `yield` expressions -/// inside the generator. +/// inside the coroutine. /// * `GY`: The "yield type", which is the type of values passed to -/// `yield` inside the generator. +/// `yield` inside the coroutine. /// * `GR`: The "return type", which is the type of value returned upon -/// completion of the generator. -/// * `GW`: The "generator witness". +/// completion of the coroutine. +/// * `GW`: The "coroutine witness". #[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable, Lift)] pub struct ClosureArgs<'tcx> { /// Lifetime and type parameters from the enclosing function, @@ -367,7 +367,7 @@ pub struct CoroutineArgsParts<'tcx, T> { impl<'tcx> CoroutineArgs<'tcx> { /// Construct `CoroutineArgs` from `CoroutineArgsParts`, containing `Args` - /// for the generator parent, alongside additional generator-specific components. + /// for the coroutine parent, alongside additional coroutine-specific components. pub fn new( tcx: TyCtxt<'tcx>, parts: CoroutineArgsParts<'tcx, Ty<'tcx>>, @@ -389,7 +389,7 @@ impl<'tcx> CoroutineArgs<'tcx> { } } - /// Divides the generator args into their respective components. + /// Divides the coroutine args into their respective components. /// The ordering assumed here must match that used by `CoroutineArgs::new` above. fn split(self) -> CoroutineArgsParts<'tcx, GenericArg<'tcx>> { match self.args[..] { @@ -403,34 +403,34 @@ impl<'tcx> CoroutineArgs<'tcx> { tupled_upvars_ty, } } - _ => bug!("generator args missing synthetics"), + _ => bug!("coroutine args missing synthetics"), } } /// Returns `true` only if enough of the synthetic types are known to /// allow using all of the methods on `CoroutineArgs` without panicking. /// - /// Used primarily by `ty::print::pretty` to be able to handle generator + /// Used primarily by `ty::print::pretty` to be able to handle coroutine /// types that haven't had their synthetic types substituted in. pub fn is_valid(self) -> bool { self.args.len() >= 5 && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_)) } - /// Returns the substitutions of the generator's parent. + /// Returns the substitutions of the coroutine's parent. pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] { self.split().parent_args } - /// This describes the types that can be contained in a generator. + /// This describes the types that can be contained in a coroutine. /// It will be a type variable initially and unified in the last stages of typeck of a body. - /// It contains a tuple of all the types that could end up on a generator frame. + /// It contains a tuple of all the types that could end up on a coroutine frame. /// The state transformation MIR pass may only produce layouts which mention types /// in this tuple. Upvars are not counted here. pub fn witness(self) -> Ty<'tcx> { self.split().witness.expect_ty() } - /// Returns an iterator over the list of types of captured paths by the generator. + /// Returns an iterator over the list of types of captured paths by the coroutine. /// In case there was a type error in figuring out the types of the captured path, an /// empty iterator is returned. #[inline] @@ -443,28 +443,28 @@ impl<'tcx> CoroutineArgs<'tcx> { } } - /// Returns the tuple type representing the upvars for this generator. + /// Returns the tuple type representing the upvars for this coroutine. #[inline] pub fn tupled_upvars_ty(self) -> Ty<'tcx> { self.split().tupled_upvars_ty.expect_ty() } - /// Returns the type representing the resume type of the generator. + /// Returns the type representing the resume type of the coroutine. pub fn resume_ty(self) -> Ty<'tcx> { self.split().resume_ty.expect_ty() } - /// Returns the type representing the yield type of the generator. + /// Returns the type representing the yield type of the coroutine. pub fn yield_ty(self) -> Ty<'tcx> { self.split().yield_ty.expect_ty() } - /// Returns the type representing the return type of the generator. + /// Returns the type representing the return type of the coroutine. pub fn return_ty(self) -> Ty<'tcx> { self.split().return_ty.expect_ty() } - /// Returns the "generator signature", which consists of its yield + /// Returns the "coroutine signature", which consists of its yield /// and return types. /// /// N.B., some bits of the code prefers to see this wrapped in a @@ -474,7 +474,7 @@ impl<'tcx> CoroutineArgs<'tcx> { ty::Binder::dummy(self.sig()) } - /// Returns the "generator signature", which consists of its resume, yield + /// Returns the "coroutine signature", which consists of its resume, yield /// and return types. pub fn sig(self) -> GenSig<'tcx> { ty::GenSig { @@ -497,11 +497,11 @@ impl<'tcx> CoroutineArgs<'tcx> { const RETURNED_NAME: &'static str = "Returned"; const POISONED_NAME: &'static str = "Panicked"; - /// The valid variant indices of this generator. + /// The valid variant indices of this coroutine. #[inline] pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> { // FIXME requires optimized MIR - FIRST_VARIANT..tcx.generator_layout(def_id).unwrap().variant_fields.next_index() + FIRST_VARIANT..tcx.coroutine_layout(def_id).unwrap().variant_fields.next_index() } /// The discriminant for the given variant. Panics if the `variant_index` is @@ -519,7 +519,7 @@ impl<'tcx> CoroutineArgs<'tcx> { Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) } } - /// The set of all discriminants for the generator, enumerated with their + /// The set of all discriminants for the coroutine, enumerated with their /// variant indices. #[inline] pub fn discriminants( @@ -543,14 +543,14 @@ impl<'tcx> CoroutineArgs<'tcx> { } } - /// The type of the state discriminant used in the generator type. + /// The type of the state discriminant used in the coroutine type. #[inline] pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { tcx.types.u32 } /// This returns the types of the MIR locals which had to be stored across suspension points. - /// It is calculated in rustc_mir_transform::generator::StateTransform. + /// It is calculated in rustc_mir_transform::coroutine::StateTransform. /// All the types here must be in the tuple in CoroutineInterior. /// /// The locals are grouped by their variant number. Note that some locals may @@ -561,7 +561,7 @@ impl<'tcx> CoroutineArgs<'tcx> { def_id: DefId, tcx: TyCtxt<'tcx>, ) -> impl Iterator<Item: Iterator<Item = Ty<'tcx>> + Captures<'tcx>> { - let layout = tcx.generator_layout(def_id).unwrap(); + let layout = tcx.coroutine_layout(def_id).unwrap(); layout.variant_fields.iter().map(move |variant| { variant.iter().map(move |field| { ty::EarlyBinder::bind(layout.field_tys[*field].ty).instantiate(tcx, self.args) @@ -569,7 +569,7 @@ impl<'tcx> CoroutineArgs<'tcx> { }) } - /// This is the types of the fields of a generator which are not stored in a + /// This is the types of the fields of a coroutine which are not stored in a /// variant. #[inline] pub fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> { @@ -584,14 +584,14 @@ pub enum UpvarArgs<'tcx> { } impl<'tcx> UpvarArgs<'tcx> { - /// Returns an iterator over the list of types of captured paths by the closure/generator. + /// Returns an iterator over the list of types of captured paths by the closure/coroutine. /// In case there was a type error in figuring out the types of the captured path, an /// empty iterator is returned. #[inline] pub fn upvar_tys(self) -> &'tcx List<Ty<'tcx>> { let tupled_tys = match self { UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(), - UpvarArgs::Coroutine(args) => args.as_generator().tupled_upvars_ty(), + UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(), }; match tupled_tys.kind() { @@ -606,7 +606,7 @@ impl<'tcx> UpvarArgs<'tcx> { pub fn tupled_upvars_ty(self) -> Ty<'tcx> { match self { UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(), - UpvarArgs::Coroutine(args) => args.as_generator().tupled_upvars_ty(), + UpvarArgs::Coroutine(args) => args.as_coroutine().tupled_upvars_ty(), } } } @@ -2165,22 +2165,22 @@ impl<'tcx> Ty<'tcx> { } #[inline] - pub fn new_generator( + pub fn new_coroutine( tcx: TyCtxt<'tcx>, def_id: DefId, - generator_args: GenericArgsRef<'tcx>, + coroutine_args: GenericArgsRef<'tcx>, movability: hir::Movability, ) -> Ty<'tcx> { debug_assert_eq!( - generator_args.len(), + coroutine_args.len(), tcx.generics_of(tcx.typeck_root_def_id(def_id)).count() + 5, - "generator constructed with incorrect number of substitutions" + "coroutine constructed with incorrect number of substitutions" ); - Ty::new(tcx, Coroutine(def_id, generator_args, movability)) + Ty::new(tcx, Coroutine(def_id, coroutine_args, movability)) } #[inline] - pub fn new_generator_witness( + pub fn new_coroutine_witness( tcx: TyCtxt<'tcx>, id: DefId, args: GenericArgsRef<'tcx>, @@ -2495,7 +2495,7 @@ impl<'tcx> Ty<'tcx> { } #[inline] - pub fn is_generator(self) -> bool { + pub fn is_coroutine(self) -> bool { matches!(self.kind(), Coroutine(..)) } @@ -2652,13 +2652,13 @@ impl<'tcx> Ty<'tcx> { /// If the type contains variants, returns the valid range of variant indices. // - // FIXME: This requires the optimized MIR in the case of generators. + // FIXME: This requires the optimized MIR in the case of coroutines. #[inline] pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> { match self.kind() { TyKind::Adt(adt, _) => Some(adt.variant_range()), TyKind::Coroutine(def_id, args, _) => { - Some(args.as_generator().variant_range(*def_id, tcx)) + Some(args.as_coroutine().variant_range(*def_id, tcx)) } _ => None, } @@ -2667,7 +2667,7 @@ impl<'tcx> Ty<'tcx> { /// If the type contains variants, returns the variant for `variant_index`. /// Panics if `variant_index` is out of range. // - // FIXME: This requires the optimized MIR in the case of generators. + // FIXME: This requires the optimized MIR in the case of coroutines. #[inline] pub fn discriminant_for_variant( self, @@ -2679,7 +2679,7 @@ impl<'tcx> Ty<'tcx> { Some(adt.discriminant_for_variant(tcx, variant_index)) } TyKind::Coroutine(def_id, args, _) => { - Some(args.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) + Some(args.as_coroutine().discriminant_for_variant(*def_id, tcx, variant_index)) } _ => None, } @@ -2689,7 +2689,7 @@ impl<'tcx> Ty<'tcx> { pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { match self.kind() { ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx), - ty::Coroutine(_, args, _) => args.as_generator().discr_ty(tcx), + ty::Coroutine(_, args, _) => args.as_coroutine().discr_ty(tcx), ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => { let assoc_items = tcx.associated_item_def_ids( diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index a44224e4dc7..7d516410b20 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -189,9 +189,9 @@ pub struct TypeckResults<'tcx> { /// Details may be find in `rustc_hir_analysis::check::rvalue_scopes`. pub rvalue_scopes: RvalueScopes, - /// Stores the predicates that apply on generator witness types. - /// formatting modified file tests/ui/generator/retain-resume-ref.rs - pub generator_interior_predicates: + /// Stores the predicates that apply on coroutine witness types. + /// formatting modified file tests/ui/coroutine/retain-resume-ref.rs + pub coroutine_interior_predicates: LocalDefIdMap<Vec<(ty::Predicate<'tcx>, ObligationCause<'tcx>)>>, /// We sometimes treat byte string literals (which are of type `&[u8; N]`) @@ -231,7 +231,7 @@ impl<'tcx> TypeckResults<'tcx> { closure_min_captures: Default::default(), closure_fake_reads: Default::default(), rvalue_scopes: Default::default(), - generator_interior_predicates: Default::default(), + coroutine_interior_predicates: Default::default(), treat_byte_string_as_slice: Default::default(), closure_size_eval: Default::default(), offset_of_data: Default::default(), diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index ffa45e481ae..41968ae75bd 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -552,7 +552,7 @@ impl<'tcx> TyCtxt<'tcx> { } /// Returns `true` if `def_id` refers to a definition that does not have its own - /// type-checking context, i.e. closure, generator or inline const. + /// type-checking context, i.e. closure, coroutine or inline const. pub fn is_typeck_child(self, def_id: DefId) -> bool { matches!( self.def_kind(def_id), @@ -686,13 +686,13 @@ impl<'tcx> TyCtxt<'tcx> { } /// Return the set of types that should be taken into account when checking - /// trait bounds on a generator's internal state. - pub fn generator_hidden_types( + /// trait bounds on a coroutine's internal state. + pub fn coroutine_hidden_types( self, def_id: DefId, ) -> impl Iterator<Item = ty::EarlyBinder<Ty<'tcx>>> { - let generator_layout = self.mir_generator_witnesses(def_id); - generator_layout + let coroutine_layout = self.mir_coroutine_witnesses(def_id); + coroutine_layout .as_ref() .map_or_else(|| [].iter(), |l| l.field_tys.iter()) .filter(|decl| !decl.ignore_for_traits) @@ -709,7 +709,7 @@ impl<'tcx> TyCtxt<'tcx> { found_recursion: false, found_any_recursion: false, check_recursion: false, - expand_generators: false, + expand_coroutines: false, tcx: self, }; val.fold_with(&mut visitor) @@ -729,7 +729,7 @@ impl<'tcx> TyCtxt<'tcx> { found_recursion: false, found_any_recursion: false, check_recursion: true, - expand_generators: true, + expand_coroutines: true, tcx: self, }; @@ -746,9 +746,9 @@ impl<'tcx> TyCtxt<'tcx> { pub fn def_kind_descr(self, def_kind: DefKind, def_id: DefId) -> &'static str { match def_kind { DefKind::AssocFn if self.associated_item(def_id).fn_has_self_parameter => "method", - DefKind::Coroutine => match self.generator_kind(def_id).unwrap() { + DefKind::Coroutine => match self.coroutine_kind(def_id).unwrap() { rustc_hir::CoroutineKind::Async(..) => "async closure", - rustc_hir::CoroutineKind::Gen => "generator", + rustc_hir::CoroutineKind::Gen => "coroutine", }, _ => def_kind.descr(def_id), } @@ -763,7 +763,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn def_kind_descr_article(self, def_kind: DefKind, def_id: DefId) -> &'static str { match def_kind { DefKind::AssocFn if self.associated_item(def_id).fn_has_self_parameter => "a", - DefKind::Coroutine => match self.generator_kind(def_id).unwrap() { + DefKind::Coroutine => match self.coroutine_kind(def_id).unwrap() { rustc_hir::CoroutineKind::Async(..) => "an", rustc_hir::CoroutineKind::Gen => "a", }, @@ -804,7 +804,7 @@ struct OpaqueTypeExpander<'tcx> { primary_def_id: Option<DefId>, found_recursion: bool, found_any_recursion: bool, - expand_generators: bool, + expand_coroutines: bool, /// Whether or not to check for recursive opaque types. /// This is `true` when we're explicitly checking for opaque type /// recursion, and 'false' otherwise to avoid unnecessary work. @@ -842,7 +842,7 @@ impl<'tcx> OpaqueTypeExpander<'tcx> { } } - fn expand_generator(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> { + fn expand_coroutine(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> { if self.found_any_recursion { return None; } @@ -851,11 +851,11 @@ impl<'tcx> OpaqueTypeExpander<'tcx> { let expanded_ty = match self.expanded_cache.get(&(def_id, args)) { Some(expanded_ty) => *expanded_ty, None => { - for bty in self.tcx.generator_hidden_types(def_id) { + for bty in self.tcx.coroutine_hidden_types(def_id) { let hidden_ty = bty.instantiate(self.tcx, args); self.fold_ty(hidden_ty); } - let expanded_ty = Ty::new_generator_witness(self.tcx, def_id, args); + let expanded_ty = Ty::new_coroutine_witness(self.tcx, def_id, args); self.expanded_cache.insert((def_id, args), expanded_ty); expanded_ty } @@ -882,14 +882,14 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> { fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { let mut t = if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) = *t.kind() { self.expand_opaque_ty(def_id, args).unwrap_or(t) - } else if t.has_opaque_types() || t.has_generators() { + } else if t.has_opaque_types() || t.has_coroutines() { t.super_fold_with(self) } else { t }; - if self.expand_generators { + if self.expand_coroutines { if let ty::CoroutineWitness(def_id, args) = *t.kind() { - t = self.expand_generator(def_id, args).unwrap_or(t); + t = self.expand_coroutine(def_id, args).unwrap_or(t); } } t @@ -1419,7 +1419,7 @@ pub fn reveal_opaque_types_in_bounds<'tcx>( found_recursion: false, found_any_recursion: false, check_recursion: false, - expand_generators: false, + expand_coroutines: false, tcx, }; val.fold_with(&mut visitor) diff --git a/compiler/rustc_middle/src/ty/visit.rs b/compiler/rustc_middle/src/ty/visit.rs index 5deb5bfb19e..15de9948644 100644 --- a/compiler/rustc_middle/src/ty/visit.rs +++ b/compiler/rustc_middle/src/ty/visit.rs @@ -47,7 +47,7 @@ pub trait TypeVisitableExt<'tcx>: TypeVisitable<TyCtxt<'tcx>> { fn has_opaque_types(&self) -> bool { self.has_type_flags(TypeFlags::HAS_TY_OPAQUE) } - fn has_generators(&self) -> bool { + fn has_coroutines(&self) -> bool { self.has_type_flags(TypeFlags::HAS_TY_GENERATOR) } fn references_error(&self) -> bool { diff --git a/compiler/rustc_mir_build/src/build/custom/mod.rs b/compiler/rustc_mir_build/src/build/custom/mod.rs index a81f70e3346..3de2f45ad9a 100644 --- a/compiler/rustc_mir_build/src/build/custom/mod.rs +++ b/compiler/rustc_mir_build/src/build/custom/mod.rs @@ -48,7 +48,7 @@ pub(super) fn build_custom_mir<'tcx>( source: MirSource::item(did), phase: MirPhase::Built, source_scopes: IndexVec::new(), - generator: None, + coroutine: None, local_decls: IndexVec::new(), user_type_annotations: IndexVec::new(), arg_count: params.len(), diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/build/expr/as_place.rs index 4aff406b376..c6a09f6568a 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -75,7 +75,7 @@ pub(in crate::build) struct PlaceBuilder<'tcx> { /// Given a list of MIR projections, convert them to list of HIR ProjectionKind. /// The projections are truncated to represent a path that might be captured by a -/// closure/generator. This implies the vector returned from this function doesn't contain +/// closure/coroutine. This implies the vector returned from this function doesn't contain /// ProjectionElems `Downcast`, `ConstantIndex`, `Index`, or `Subslice` because those will never be /// part of a path that is captured by a closure. We stop applying projections once we see the first /// projection that isn't captured by a closure. @@ -213,7 +213,7 @@ fn to_upvars_resolved_place_builder<'tcx>( /// projections. /// /// Supports only HIR projection kinds that represent a path that might be -/// captured by a closure or a generator, i.e., an `Index` or a `Subslice` +/// captured by a closure or a coroutine, i.e., an `Index` or a `Subslice` /// projection kinds are unsupported. fn strip_prefix<'a, 'tcx>( mut base_ty: Ty<'tcx>, diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index d9858a66aa8..eece8684e36 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs @@ -181,7 +181,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { block = success; // The `Box<T>` temporary created here is not a part of the HIR, - // and therefore is not considered during generator auto-trait + // and therefore is not considered during coroutine auto-trait // determination. See the comment about `box` at `yield_in_scope`. let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span)); this.cfg.push( diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index a4de42d45c9..054661cf237 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -547,7 +547,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { source_info, TerminatorKind::Yield { value, resume, resume_arg: destination, drop: None }, ); - this.generator_drop_cleanup(block); + this.coroutine_drop_cleanup(block); resume.unit() } diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index aaea10f3d62..8a3b67b8f03 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -173,7 +173,7 @@ struct Builder<'a, 'tcx> { check_overflow: bool, fn_span: Span, arg_count: usize, - generator_kind: Option<CoroutineKind>, + coroutine_kind: Option<CoroutineKind>, /// The current set of scopes, updated as we traverse; /// see the `scope` module for more details. @@ -448,7 +448,7 @@ fn construct_fn<'tcx>( ) -> Body<'tcx> { let span = tcx.def_span(fn_def); let fn_id = tcx.hir().local_def_id_to_hir_id(fn_def); - let generator_kind = tcx.generator_kind(fn_def); + let coroutine_kind = tcx.coroutine_kind(fn_def); // The representation of thir for `-Zunpretty=thir-tree` relies on // the entry expression being the last element of `thir.exprs`. @@ -478,12 +478,12 @@ fn construct_fn<'tcx>( let arguments = &thir.params; - let (yield_ty, return_ty) = if generator_kind.is_some() { + let (yield_ty, return_ty) = if coroutine_kind.is_some() { let gen_ty = arguments[thir::UPVAR_ENV_PARAM].ty; let gen_sig = match gen_ty.kind() { - ty::Coroutine(_, gen_args, ..) => gen_args.as_generator().sig(), + ty::Coroutine(_, gen_args, ..) => gen_args.as_coroutine().sig(), _ => { - span_bug!(span, "generator w/o generator type: {:?}", gen_ty) + span_bug!(span, "coroutine w/o coroutine type: {:?}", gen_ty) } }; (Some(gen_sig.yield_ty), gen_sig.return_ty) @@ -519,7 +519,7 @@ fn construct_fn<'tcx>( safety, return_ty, return_ty_span, - generator_kind, + coroutine_kind, ); let call_site_scope = @@ -553,7 +553,7 @@ fn construct_fn<'tcx>( None }; if yield_ty.is_some() { - body.generator.as_mut().unwrap().yield_ty = yield_ty; + body.coroutine.as_mut().unwrap().yield_ty = yield_ty; } body } @@ -619,7 +619,7 @@ fn construct_const<'a, 'tcx>( fn construct_error(tcx: TyCtxt<'_>, def: LocalDefId, err: ErrorGuaranteed) -> Body<'_> { let span = tcx.def_span(def); let hir_id = tcx.hir().local_def_id_to_hir_id(def); - let generator_kind = tcx.generator_kind(def); + let coroutine_kind = tcx.coroutine_kind(def); let body_owner_kind = tcx.hir().body_owner_kind(def); let ty = Ty::new_error(tcx, err); @@ -630,7 +630,7 @@ fn construct_error(tcx: TyCtxt<'_>, def: LocalDefId, err: ErrorGuaranteed) -> Bo match ty.kind() { ty::Closure(_, args) => 1 + args.as_closure().sig().inputs().skip_binder().len(), ty::Coroutine(..) => 2, - _ => bug!("expected closure or generator, found {ty:?}"), + _ => bug!("expected closure or coroutine, found {ty:?}"), } } hir::BodyOwnerKind::Const { .. } => 0, @@ -669,10 +669,10 @@ fn construct_error(tcx: TyCtxt<'_>, def: LocalDefId, err: ErrorGuaranteed) -> Bo num_params, vec![], span, - generator_kind, + coroutine_kind, Some(err), ); - body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty)); + body.coroutine.as_mut().map(|gen| gen.yield_ty = Some(ty)); body } @@ -687,7 +687,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { safety: Safety, return_ty: Ty<'tcx>, return_span: Span, - generator_kind: Option<CoroutineKind>, + coroutine_kind: Option<CoroutineKind>, ) -> Builder<'a, 'tcx> { let tcx = infcx.tcx; let attrs = tcx.hir().attrs(hir_id); @@ -718,7 +718,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { cfg: CFG { basic_blocks: IndexVec::new() }, fn_span: span, arg_count, - generator_kind, + coroutine_kind, scopes: scope::Scopes::new(), block_context: BlockContext::new(), source_scopes: IndexVec::new(), @@ -760,7 +760,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.arg_count, self.var_debug_info, self.fn_span, - self.generator_kind, + self.coroutine_kind, None, ) } diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/build/scope.rs index 4ccd2ecaac1..b3d3863b5db 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/build/scope.rs @@ -109,7 +109,7 @@ pub struct Scopes<'tcx> { unwind_drops: DropTree, /// Drops that need to be done on paths to the `CoroutineDrop` terminator. - generator_drops: DropTree, + coroutine_drops: DropTree, } #[derive(Debug)] @@ -133,8 +133,8 @@ struct Scope { cached_unwind_block: Option<DropIdx>, /// The drop index that will drop everything in and below this scope on a - /// generator drop path. - cached_generator_drop_block: Option<DropIdx>, + /// coroutine drop path. + cached_coroutine_drop_block: Option<DropIdx>, } #[derive(Clone, Copy, Debug)] @@ -194,7 +194,7 @@ const ROOT_NODE: DropIdx = DropIdx::from_u32(0); /// A tree of drops that we have deferred lowering. It's used for: /// /// * Drops on unwind paths -/// * Drops on generator drop paths (when a suspended generator is dropped) +/// * Drops on coroutine drop paths (when a suspended coroutine is dropped) /// * Drops on return and loop exit paths /// * Drops on the else path in an `if let` chain /// @@ -222,8 +222,8 @@ impl Scope { /// * polluting the cleanup MIR with StorageDead creates /// landing pads even though there's no actual destructors /// * freeing up stack space has no effect during unwinding - /// Note that for generators we do emit StorageDeads, for the - /// use of optimizations in the MIR generator transform. + /// Note that for coroutines we do emit StorageDeads, for the + /// use of optimizations in the MIR coroutine transform. fn needs_cleanup(&self) -> bool { self.drops.iter().any(|drop| match drop.kind { DropKind::Value => true, @@ -233,7 +233,7 @@ impl Scope { fn invalidate_cache(&mut self) { self.cached_unwind_block = None; - self.cached_generator_drop_block = None; + self.cached_coroutine_drop_block = None; } } @@ -407,7 +407,7 @@ impl<'tcx> Scopes<'tcx> { breakable_scopes: Vec::new(), if_then_scope: None, unwind_drops: DropTree::new(), - generator_drops: DropTree::new(), + coroutine_drops: DropTree::new(), } } @@ -419,7 +419,7 @@ impl<'tcx> Scopes<'tcx> { drops: vec![], moved_locals: vec![], cached_unwind_block: None, - cached_generator_drop_block: None, + cached_coroutine_drop_block: None, }); } @@ -734,7 +734,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // If we are emitting a `drop` statement, we need to have the cached // diverge cleanup pads ready in case that drop panics. let needs_cleanup = self.scopes.scopes.last().is_some_and(|scope| scope.needs_cleanup()); - let is_generator = self.generator_kind.is_some(); + let is_coroutine = self.coroutine_kind.is_some(); let unwind_to = if needs_cleanup { self.diverge_cleanup() } else { DropIdx::MAX }; let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes"); @@ -744,7 +744,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { scope, block, unwind_to, - is_generator && needs_cleanup, + is_coroutine && needs_cleanup, self.arg_count, )) } @@ -984,11 +984,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // caches gets invalidated. i.e., if a new drop is added into the middle scope, the // cache of outer scope stays intact. // - // Since we only cache drops for the unwind path and the generator drop + // Since we only cache drops for the unwind path and the coroutine drop // path, we only need to invalidate the cache for drops that happen on - // the unwind or generator drop paths. This means that for - // non-generators we don't need to invalidate caches for `DropKind::Storage`. - let invalidate_caches = needs_drop || self.generator_kind.is_some(); + // the unwind or coroutine drop paths. This means that for + // non-coroutines we don't need to invalidate caches for `DropKind::Storage`. + let invalidate_caches = needs_drop || self.coroutine_kind.is_some(); for scope in self.scopes.scopes.iter_mut().rev() { if invalidate_caches { scope.invalidate_cache(); @@ -1101,10 +1101,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { return cached_drop; } - let is_generator = self.generator_kind.is_some(); + let is_coroutine = self.coroutine_kind.is_some(); for scope in &mut self.scopes.scopes[uncached_scope..=target] { for drop in &scope.drops { - if is_generator || drop.kind == DropKind::Value { + if is_coroutine || drop.kind == DropKind::Value { cached_drop = self.scopes.unwind_drops.add_drop(*drop, cached_drop); } } @@ -1137,17 +1137,17 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } /// Sets up a path that performs all required cleanup for dropping a - /// generator, starting from the given block that ends in + /// coroutine, starting from the given block that ends in /// [TerminatorKind::Yield]. /// /// This path terminates in CoroutineDrop. - pub(crate) fn generator_drop_cleanup(&mut self, yield_block: BasicBlock) { + pub(crate) fn coroutine_drop_cleanup(&mut self, yield_block: BasicBlock) { debug_assert!( matches!( self.cfg.block_data(yield_block).terminator().kind, TerminatorKind::Yield { .. } ), - "generator_drop_cleanup called on block with non-yield terminator." + "coroutine_drop_cleanup called on block with non-yield terminator." ); let (uncached_scope, mut cached_drop) = self .scopes @@ -1156,18 +1156,18 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { .enumerate() .rev() .find_map(|(scope_idx, scope)| { - scope.cached_generator_drop_block.map(|cached_block| (scope_idx + 1, cached_block)) + scope.cached_coroutine_drop_block.map(|cached_block| (scope_idx + 1, cached_block)) }) .unwrap_or((0, ROOT_NODE)); for scope in &mut self.scopes.scopes[uncached_scope..] { for drop in &scope.drops { - cached_drop = self.scopes.generator_drops.add_drop(*drop, cached_drop); + cached_drop = self.scopes.coroutine_drops.add_drop(*drop, cached_drop); } - scope.cached_generator_drop_block = Some(cached_drop); + scope.cached_coroutine_drop_block = Some(cached_drop); } - self.scopes.generator_drops.add_entry(yield_block, cached_drop); + self.scopes.coroutine_drops.add_entry(yield_block, cached_drop); } /// Utility function for *non*-scope code to build their own drops @@ -1274,7 +1274,7 @@ fn build_scope_drops<'tcx>( // drops panic (panicking while unwinding will abort, so there's no need for // another set of arrows). // - // For generators, we unwind from a drop on a local to its StorageDead + // For coroutines, we unwind from a drop on a local to its StorageDead // statement. For other functions we don't worry about StorageDead. The // drops for the unwind path should have already been generated by // `diverge_cleanup_gen`. @@ -1346,7 +1346,7 @@ impl<'a, 'tcx: 'a> Builder<'a, 'tcx> { blocks[ROOT_NODE] = continue_block; drops.build_mir::<ExitScopes>(&mut self.cfg, &mut blocks); - let is_generator = self.generator_kind.is_some(); + let is_coroutine = self.coroutine_kind.is_some(); // Link the exit drop tree to unwind drop tree. if drops.drops.iter().any(|(drop, _)| drop.kind == DropKind::Value) { @@ -1355,7 +1355,7 @@ impl<'a, 'tcx: 'a> Builder<'a, 'tcx> { for (drop_idx, drop_data) in drops.drops.iter_enumerated().skip(1) { match drop_data.0.kind { DropKind::Storage => { - if is_generator { + if is_coroutine { let unwind_drop = self .scopes .unwind_drops @@ -1381,10 +1381,10 @@ impl<'a, 'tcx: 'a> Builder<'a, 'tcx> { blocks[ROOT_NODE].map(BasicBlock::unit) } - /// Build the unwind and generator drop trees. + /// Build the unwind and coroutine drop trees. pub(crate) fn build_drop_trees(&mut self) { - if self.generator_kind.is_some() { - self.build_generator_drop_trees(); + if self.coroutine_kind.is_some() { + self.build_coroutine_drop_trees(); } else { Self::build_unwind_tree( &mut self.cfg, @@ -1395,9 +1395,9 @@ impl<'a, 'tcx: 'a> Builder<'a, 'tcx> { } } - fn build_generator_drop_trees(&mut self) { - // Build the drop tree for dropping the generator while it's suspended. - let drops = &mut self.scopes.generator_drops; + fn build_coroutine_drop_trees(&mut self) { + // Build the drop tree for dropping the coroutine while it's suspended. + let drops = &mut self.scopes.coroutine_drops; let cfg = &mut self.cfg; let fn_span = self.fn_span; let mut blocks = IndexVec::from_elem(None, &drops.drops); @@ -1416,11 +1416,11 @@ impl<'a, 'tcx: 'a> Builder<'a, 'tcx> { Self::build_unwind_tree(cfg, unwind_drops, fn_span, resume_block); // Build the drop tree for unwinding when dropping a suspended - // generator. + // coroutine. // // This is a different tree to the standard unwind paths here to // prevent drop elaboration from creating drop flags that would have - // to be captured by the generator. I'm not sure how important this + // to be captured by the coroutine. I'm not sure how important this // optimization is, but it is here. for (drop_idx, drop_data) in drops.drops.iter_enumerated() { if let DropKind::Value = drop_data.0.kind { @@ -1474,7 +1474,7 @@ impl<'tcx> DropTreeBuilder<'tcx> for CoroutineDrop { } else { span_bug!( term.source_info.span, - "cannot enter generator drop tree from {:?}", + "cannot enter coroutine drop tree from {:?}", term.kind ) } diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 2d221b826c9..00d2afce8c6 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -121,7 +121,7 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> { self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, self.hir_context).0 == Level::Allow } - /// Handle closures/generators/inline-consts, which is unsafecked with their parent body. + /// Handle closures/coroutines/inline-consts, which is unsafecked with their parent body. fn visit_inner_body(&mut self, def: LocalDefId) { if let Ok((inner_thir, expr)) = self.tcx.thir_body(def) { let inner_thir = &inner_thir.borrow(); diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index 8bd4af02484..25ba67a63ec 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -860,13 +860,13 @@ where let ty = self.place_ty(self.place); match ty.kind() { ty::Closure(_, args) => self.open_drop_for_tuple(&args.as_closure().upvar_tys()), - // Note that `elaborate_drops` only drops the upvars of a generator, + // Note that `elaborate_drops` only drops the upvars of a coroutine, // and this is ok because `open_drop` here can only be reached - // within that own generator's resume function. + // within that own coroutine's resume function. // This should only happen for the self argument on the resume function. - // It effectively only contains upvars until the generator transformation runs. - // See librustc_body/transform/generator.rs for more details. - ty::Coroutine(_, args, _) => self.open_drop_for_tuple(&args.as_generator().upvar_tys()), + // It effectively only contains upvars until the coroutine transformation runs. + // See librustc_body/transform/coroutine.rs for more details. + ty::Coroutine(_, args, _) => self.open_drop_for_tuple(&args.as_coroutine().upvar_tys()), ty::Tuple(fields) => self.open_drop_for_tuple(fields), ty::Adt(def, args) => self.open_drop_for_adt(*def, args), ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind), diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index bdddaaebca4..c12ccba1e5c 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -267,7 +267,7 @@ where mir::TerminatorKind::Yield { resume, resume_arg, .. } => { self.write_row(w, "", "(on yield resume)", |this, w, fmt| { - let state_on_generator_drop = this.results.get().clone(); + let state_on_coroutine_drop = this.results.get().clone(); this.results.apply_custom_effect(|analysis, state| { analysis.apply_call_return_effect( state, @@ -283,7 +283,7 @@ where fmt = fmt, diff = diff_pretty( this.results.get(), - &state_on_generator_drop, + &state_on_coroutine_drop, this.results.analysis() ), ) diff --git a/compiler/rustc_mir_dataflow/src/framework/mod.rs b/compiler/rustc_mir_dataflow/src/framework/mod.rs index ce30c642fcc..b785a999f08 100644 --- a/compiler/rustc_mir_dataflow/src/framework/mod.rs +++ b/compiler/rustc_mir_dataflow/src/framework/mod.rs @@ -114,7 +114,7 @@ pub trait AnalysisDomain<'tcx> { // // FIXME: For backward dataflow analyses, the initial state should be applied to every basic // block where control flow could exit the MIR body (e.g., those terminated with `return` or - // `resume`). It's not obvious how to handle `yield` points in generators, however. + // `resume`). It's not obvious how to handle `yield` points in coroutines, however. fn initialize_start_block(&self, body: &mir::Body<'tcx>, state: &mut Self::Domain); } diff --git a/compiler/rustc_mir_dataflow/src/impls/borrowed_locals.rs b/compiler/rustc_mir_dataflow/src/impls/borrowed_locals.rs index 20d1edbc35b..1e8e09ac333 100644 --- a/compiler/rustc_mir_dataflow/src/impls/borrowed_locals.rs +++ b/compiler/rustc_mir_dataflow/src/impls/borrowed_locals.rs @@ -9,7 +9,7 @@ use crate::{AnalysisDomain, GenKill, GenKillAnalysis}; /// /// At present, this is used as a very limited form of alias analysis. For example, /// `MaybeBorrowedLocals` is used to compute which locals are live during a yield expression for -/// immovable generators. +/// immovable coroutines. #[derive(Clone, Copy)] pub struct MaybeBorrowedLocals; diff --git a/compiler/rustc_mir_dataflow/src/impls/initialized.rs b/compiler/rustc_mir_dataflow/src/impls/initialized.rs index 118ae87e1f1..182f2590137 100644 --- a/compiler/rustc_mir_dataflow/src/impls/initialized.rs +++ b/compiler/rustc_mir_dataflow/src/impls/initialized.rs @@ -763,7 +763,7 @@ fn switch_on_enum_discriminant<'mir, 'tcx>( ty::Adt(def, _) => return Some((*discriminated, *def)), // `Rvalue::Discriminant` is also used to get the active yield point for a - // generator, but we do not need edge-specific effects in that case. This may + // coroutine, but we do not need edge-specific effects in that case. This may // change in the future. ty::Coroutine(..) => return None, diff --git a/compiler/rustc_mir_dataflow/src/impls/liveness.rs b/compiler/rustc_mir_dataflow/src/impls/liveness.rs index 5aa73c7a906..c1152e88cd0 100644 --- a/compiler/rustc_mir_dataflow/src/impls/liveness.rs +++ b/compiler/rustc_mir_dataflow/src/impls/liveness.rs @@ -98,7 +98,7 @@ where { fn visit_place(&mut self, place: &mir::Place<'tcx>, context: PlaceContext, location: Location) { if let PlaceContext::MutatingUse(MutatingUseContext::Yield) = context { - // The resume place is evaluated and assigned to only after generator resumes, so its + // The resume place is evaluated and assigned to only after coroutine resumes, so its // effect is handled separately in `call_resume_effect`. return; } diff --git a/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs b/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs index 8d37f50ed8d..5a58e3af8be 100644 --- a/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs +++ b/compiler/rustc_mir_dataflow/src/impls/storage_liveness.rs @@ -268,7 +268,7 @@ impl<'tcx> crate::GenKillAnalysis<'tcx> for MaybeRequiresStorage<'_, '_, 'tcx> { // Note that we do *not* gen the `resume_arg` of `Yield` terminators. The reason for // that is that a `yield` will return from the function, and `resume_arg` is written - // only when the generator is later resumed. Unlike `Call`, this doesn't require the + // only when the coroutine is later resumed. Unlike `Call`, this doesn't require the // place to have storage *before* the yield, only after. TerminatorKind::Yield { .. } => {} diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 47926e63eda..04108aeedf6 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -915,7 +915,7 @@ impl Map { ) { for sibling in self.children(parent) { let elem = self.places[sibling].proj_elem; - // Only invalidate variants and discriminant. Fields (for generators) are not + // Only invalidate variants and discriminant. Fields (for coroutines) are not // invalidated by assignment to a variant. if let Some(TrackElem::Variant(..) | TrackElem::Discriminant) = elem // Only invalidate the other variants, the current one is fine. diff --git a/compiler/rustc_mir_transform/src/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs index 0a48e0d3fdf..53c0d0dea29 100644 --- a/compiler/rustc_mir_transform/src/const_prop.rs +++ b/compiler/rustc_mir_transform/src/const_prop.rs @@ -82,11 +82,11 @@ impl<'tcx> MirPass<'tcx> for ConstProp { return; } - // FIXME(welseywiser) const prop doesn't work on generators because of query cycles + // FIXME(welseywiser) const prop doesn't work on coroutines because of query cycles // computing their layout. - let is_generator = def_kind == DefKind::Coroutine; - if is_generator { - trace!("ConstProp skipped for generator {:?}", def_id); + let is_coroutine = def_kind == DefKind::Coroutine; + if is_coroutine { + trace!("ConstProp skipped for coroutine {:?}", def_id); return; } @@ -512,7 +512,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { fn replace_with_const(&mut self, place: Place<'tcx>) -> Option<Const<'tcx>> { // This will return None if the above `const_prop` invocation only "wrote" a - // type whose creation requires no write. E.g. a generator whose initial state + // type whose creation requires no write. E.g. a coroutine whose initial state // consists solely of uninitialized memory (so it doesn't capture any locals). let value = self.get_const(place)?; if !self.tcx.consider_optimizing(|| format!("ConstantPropagation - {value:?}")) { diff --git a/compiler/rustc_mir_transform/src/const_prop_lint.rs b/compiler/rustc_mir_transform/src/const_prop_lint.rs index 22f84e37637..a23ba9c4aa9 100644 --- a/compiler/rustc_mir_transform/src/const_prop_lint.rs +++ b/compiler/rustc_mir_transform/src/const_prop_lint.rs @@ -59,10 +59,10 @@ impl<'tcx> MirLint<'tcx> for ConstPropLint { return; } - // FIXME(welseywiser) const prop doesn't work on generators because of query cycles + // FIXME(welseywiser) const prop doesn't work on coroutines because of query cycles // computing their layout. if let DefKind::Coroutine = def_kind { - trace!("ConstPropLint skipped for generator {:?}", def_id); + trace!("ConstPropLint skipped for coroutine {:?}", def_id); return; } diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/coroutine.rs index 696cb4e644b..fa56d59dd80 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -1,22 +1,22 @@ -//! This is the implementation of the pass which transforms generators into state machines. +//! This is the implementation of the pass which transforms coroutines into state machines. //! -//! MIR generation for generators creates a function which has a self argument which -//! passes by value. This argument is effectively a generator type which only contains upvars and -//! is only used for this argument inside the MIR for the generator. +//! MIR generation for coroutines creates a function which has a self argument which +//! passes by value. This argument is effectively a coroutine type which only contains upvars and +//! is only used for this argument inside the MIR for the coroutine. //! It is passed by value to enable upvars to be moved out of it. Drop elaboration runs on that //! MIR before this pass and creates drop flags for MIR locals. -//! It will also drop the generator argument (which only consists of upvars) if any of the upvars -//! are moved out of. This pass elaborates the drops of upvars / generator argument in the case +//! It will also drop the coroutine argument (which only consists of upvars) if any of the upvars +//! are moved out of. This pass elaborates the drops of upvars / coroutine argument in the case //! that none of the upvars were moved out of. This is because we cannot have any drops of this -//! generator in the MIR, since it is used to create the drop glue for the generator. We'd get +//! coroutine in the MIR, since it is used to create the drop glue for the coroutine. We'd get //! infinite recursion otherwise. //! //! This pass creates the implementation for either the `Coroutine::resume` or `Future::poll` -//! function and the drop shim for the generator based on the MIR input. -//! It converts the generator argument from Self to &mut Self adding derefs in the MIR as needed. -//! It computes the final layout of the generator struct which looks like this: +//! function and the drop shim for the coroutine based on the MIR input. +//! It converts the coroutine argument from Self to &mut Self adding derefs in the MIR as needed. +//! It computes the final layout of the coroutine struct which looks like this: //! First upvars are stored -//! It is followed by the generator state field. +//! It is followed by the coroutine state field. //! Then finally the MIR locals which are live across a suspension point are stored. //! ```ignore (illustrative) //! struct Coroutine { @@ -26,28 +26,28 @@ //! } //! ``` //! This pass computes the meaning of the state field and the MIR locals which are live -//! across a suspension point. There are however three hardcoded generator states: +//! across a suspension point. There are however three hardcoded coroutine states: //! 0 - Coroutine have not been resumed yet //! 1 - Coroutine has returned / is completed //! 2 - Coroutine has been poisoned //! -//! It also rewrites `return x` and `yield y` as setting a new generator state and returning +//! It also rewrites `return x` and `yield y` as setting a new coroutine state and returning //! `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`, //! or `Poll::Ready(x)` and `Poll::Pending` respectively. -//! MIR locals which are live across a suspension point are moved to the generator struct -//! with references to them being updated with references to the generator struct. +//! MIR locals which are live across a suspension point are moved to the coroutine struct +//! with references to them being updated with references to the coroutine struct. //! -//! The pass creates two functions which have a switch on the generator state giving +//! The pass creates two functions which have a switch on the coroutine state giving //! the action to take. //! //! One of them is the implementation of `Coroutine::resume` / `Future::poll`. -//! For generators with state 0 (unresumed) it starts the execution of the generator. -//! For generators with state 1 (returned) and state 2 (poisoned) it panics. +//! For coroutines with state 0 (unresumed) it starts the execution of the coroutine. +//! For coroutines with state 1 (returned) and state 2 (poisoned) it panics. //! Otherwise it continues the execution from the last suspension point. //! -//! The other function is the drop glue for the generator. -//! For generators with state 0 (unresumed) it drops the upvars of the generator. -//! For generators with state 1 (returned) and state 2 (poisoned) it does nothing. +//! The other function is the drop glue for the coroutine. +//! For coroutines with state 0 (unresumed) it drops the upvars of the coroutine. +//! For coroutines with state 1 (returned) and state 2 (poisoned) it does nothing. //! Otherwise it drops all the values in scope at the last suspension point. use crate::abort_unwinding_calls; @@ -203,12 +203,12 @@ const RETURNED: usize = CoroutineArgs::RETURNED; /// Coroutine has panicked and is poisoned. const POISONED: usize = CoroutineArgs::POISONED; -/// Number of variants to reserve in generator state. Corresponds to -/// `UNRESUMED` (beginning of a generator) and `RETURNED`/`POISONED` -/// (end of a generator) states. +/// Number of variants to reserve in coroutine state. Corresponds to +/// `UNRESUMED` (beginning of a coroutine) and `RETURNED`/`POISONED` +/// (end of a coroutine) states. const RESERVED_VARIANTS: usize = 3; -/// A `yield` point in the generator. +/// A `yield` point in the coroutine. struct SuspensionPoint<'tcx> { /// State discriminant used when suspending or resuming at this point. state: usize, @@ -216,7 +216,7 @@ struct SuspensionPoint<'tcx> { resume: BasicBlock, /// Where to move the resume argument after resumption. resume_arg: Place<'tcx>, - /// Which block to jump to if the generator is dropped in this state. + /// Which block to jump to if the coroutine is dropped in this state. drop: Option<BasicBlock>, /// Set of locals that have live storage while at this suspension point. storage_liveness: GrowableBitSet<Local>, @@ -228,10 +228,10 @@ struct TransformVisitor<'tcx> { state_adt_ref: AdtDef<'tcx>, state_args: GenericArgsRef<'tcx>, - // The type of the discriminant in the generator struct + // The type of the discriminant in the coroutine struct discr_ty: Ty<'tcx>, - // Mapping from Local to (type of local, generator struct index) + // Mapping from Local to (type of local, coroutine struct index) // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`. remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, FieldIdx)>, @@ -297,7 +297,7 @@ impl<'tcx> TransformVisitor<'tcx> { }); } - // Create a Place referencing a generator struct field + // Create a Place referencing a coroutine struct field fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> { let self_place = Place::from(SELF_ARG); let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index); @@ -349,7 +349,7 @@ impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> { _context: PlaceContext, _location: Location, ) { - // Replace an Local in the remap with a generator struct access + // Replace an Local in the remap with a coroutine struct access if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) { replace_base(place, self.make_field(variant_index, idx, ty), self.tcx); } @@ -413,7 +413,7 @@ impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> { } } -fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { +fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let gen_ty = body.local_decls.raw[1].ty; let ref_gen_ty = Ty::new_ref( @@ -422,14 +422,14 @@ fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Bo ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut }, ); - // Replace the by value generator argument + // Replace the by value coroutine argument body.local_decls.raw[1].ty = ref_gen_ty; - // Add a deref to accesses of the generator state + // Add a deref to accesses of the coroutine state DerefArgVisitor { tcx }.visit_body(body); } -fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { +fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let ref_gen_ty = body.local_decls.raw[1].ty; let pin_did = tcx.require_lang_item(LangItem::Pin, Some(body.span)); @@ -437,10 +437,10 @@ fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body let args = tcx.mk_args(&[ref_gen_ty.into()]); let pin_ref_gen_ty = Ty::new_adt(tcx, pin_adt_ref, args); - // Replace the by ref generator argument + // Replace the by ref coroutine argument body.local_decls.raw[1].ty = pin_ref_gen_ty; - // Add the Pin field access to accesses of the generator state + // Add the Pin field access to accesses of the coroutine state PinArgVisitor { ref_gen_ty, tcx }.visit_body(body); } @@ -465,7 +465,7 @@ fn replace_local<'tcx>( new_local } -/// Transforms the `body` of the generator applying the following transforms: +/// Transforms the `body` of the coroutine applying the following transforms: /// /// - Eliminates all the `get_context` calls that async lowering created. /// - Replace all `Local` `ResumeTy` types with `&mut Context<'_>` (`context_mut_ref`). @@ -485,7 +485,7 @@ fn replace_local<'tcx>( /// /// The async lowering step and the type / lifetime inference / checking are /// still using the `ResumeTy` indirection for the time being, and that indirection -/// is removed here. After this transform, the generator body only knows about `&mut Context<'_>`. +/// is removed here. After this transform, the coroutine body only knows about `&mut Context<'_>`. fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let context_mut_ref = Ty::new_task_context(tcx); @@ -601,7 +601,7 @@ fn locals_live_across_suspend_points<'tcx>( // Calculate the MIR locals which have been previously // borrowed (even if they are still active). let borrowed_locals_results = - MaybeBorrowedLocals.into_engine(tcx, body_ref).pass_name("generator").iterate_to_fixpoint(); + MaybeBorrowedLocals.into_engine(tcx, body_ref).pass_name("coroutine").iterate_to_fixpoint(); let mut borrowed_locals_cursor = borrowed_locals_results.cloned_results_cursor(body_ref); @@ -616,7 +616,7 @@ fn locals_live_across_suspend_points<'tcx>( // Calculate the liveness of MIR locals ignoring borrows. let mut liveness = MaybeLiveLocals .into_engine(tcx, body_ref) - .pass_name("generator") + .pass_name("coroutine") .iterate_to_fixpoint() .into_results_cursor(body_ref); @@ -635,8 +635,8 @@ fn locals_live_across_suspend_points<'tcx>( if !movable { // The `liveness` variable contains the liveness of MIR locals ignoring borrows. - // This is correct for movable generators since borrows cannot live across - // suspension points. However for immovable generators we need to account for + // This is correct for movable coroutines since borrows cannot live across + // suspension points. However for immovable coroutines we need to account for // borrows, so we conservatively assume that all borrowed locals are live until // we find a StorageDead statement referencing the locals. // To do this we just union our `liveness` result with `borrowed_locals`, which @@ -659,7 +659,7 @@ fn locals_live_across_suspend_points<'tcx>( requires_storage_cursor.seek_before_primary_effect(loc); live_locals.intersect(requires_storage_cursor.get()); - // The generator argument is ignored. + // The coroutine argument is ignored. live_locals.remove(SELF_ARG); debug!("loc = {:?}, live_locals = {:?}", loc, live_locals); @@ -803,7 +803,7 @@ struct StorageConflictVisitor<'mir, 'tcx, 's> { body: &'mir Body<'tcx>, saved_locals: &'s CoroutineSavedLocals, // FIXME(tmandry): Consider using sparse bitsets here once we have good - // benchmarks for generators. + // benchmarks for coroutines. local_conflicts: BitMatrix<Local, Local>, } @@ -873,7 +873,7 @@ fn compute_layout<'tcx>( let mut locals = IndexVec::<CoroutineSavedLocal, _>::new(); let mut tys = IndexVec::<CoroutineSavedLocal, _>::new(); for (saved_local, local) in saved_locals.iter_enumerated() { - debug!("generator saved local {:?} => {:?}", saved_local, local); + debug!("coroutine saved local {:?} => {:?}", saved_local, local); locals.push(local); let decl = &body.local_decls[local]; @@ -914,8 +914,8 @@ fn compute_layout<'tcx>( .copied() .collect(); - // Build the generator variant field list. - // Create a map from local indices to generator struct indices. + // Build the coroutine variant field list. + // Create a map from local indices to coroutine struct indices. let mut variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> = iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect(); let mut remap = FxHashMap::default(); @@ -926,7 +926,7 @@ fn compute_layout<'tcx>( fields.push(saved_local); // Note that if a field is included in multiple variants, we will // just use the first one here. That's fine; fields do not move - // around inside generators, so it doesn't matter which variant + // around inside coroutines, so it doesn't matter which variant // index we access them by. let idx = FieldIdx::from_usize(idx); remap.entry(locals[saved_local]).or_insert((tys[saved_local].ty, variant_index, idx)); @@ -934,8 +934,8 @@ fn compute_layout<'tcx>( variant_fields.push(fields); variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]); } - debug!("generator variant_fields = {:?}", variant_fields); - debug!("generator storage_conflicts = {:#?}", storage_conflicts); + debug!("coroutine variant_fields = {:?}", variant_fields); + debug!("coroutine storage_conflicts = {:#?}", storage_conflicts); let mut field_names = IndexVec::from_elem(None, &tys); for var in &body.var_debug_info { @@ -959,7 +959,7 @@ fn compute_layout<'tcx>( (remap, layout, storage_liveness) } -/// Replaces the entry point of `body` with a block that switches on the generator discriminant and +/// Replaces the entry point of `body` with a block that switches on the coroutine discriminant and /// dispatches to blocks according to `cases`. /// /// After this function, the former entry point of the function will be bb1. @@ -992,14 +992,14 @@ fn insert_switch<'tcx>( } } -fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { +fn elaborate_coroutine_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { use crate::shim::DropShimElaborator; use rustc_middle::mir::patch::MirPatch; use rustc_mir_dataflow::elaborate_drops::{elaborate_drop, Unwind}; - // Note that `elaborate_drops` only drops the upvars of a generator, and + // Note that `elaborate_drops` only drops the upvars of a coroutine, and // this is ok because `open_drop` can only be reached within that own - // generator's resume function. + // coroutine's resume function. let def_id = body.source.def_id(); let param_env = tcx.param_env(def_id); @@ -1047,7 +1047,7 @@ fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { elaborator.patch.apply(body); } -fn create_generator_drop_shim<'tcx>( +fn create_coroutine_drop_shim<'tcx>( tcx: TyCtxt<'tcx>, transform: &TransformVisitor<'tcx>, gen_ty: Ty<'tcx>, @@ -1078,9 +1078,9 @@ fn create_generator_drop_shim<'tcx>( // Replace the return variable body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(Ty::new_unit(tcx), source_info); - make_generator_state_argument_indirect(tcx, &mut body); + make_coroutine_state_argument_indirect(tcx, &mut body); - // Change the generator argument from &mut to *mut + // Change the coroutine argument from &mut to *mut body.local_decls[SELF_ARG] = LocalDecl::with_source_info( Ty::new_ptr(tcx, ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }), source_info, @@ -1104,10 +1104,10 @@ fn create_generator_drop_shim<'tcx>( None, ); - // Temporary change MirSource to generator's instance so that dump_mir produces more sensible + // Temporary change MirSource to coroutine's instance so that dump_mir produces more sensible // filename. body.source.instance = gen_instance; - dump_mir(tcx, false, "generator_drop", &0, &body, |_, _| Ok(())); + dump_mir(tcx, false, "coroutine_drop", &0, &body, |_, _| Ok(())); body.source.instance = drop_instance; body @@ -1191,7 +1191,7 @@ fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool { TerminatorKind::UnwindResume => {} TerminatorKind::Yield { .. } => { - unreachable!("`can_unwind` called before generator transform") + unreachable!("`can_unwind` called before coroutine transform") } // These may unwind. @@ -1206,7 +1206,7 @@ fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool { false } -fn create_generator_resume_function<'tcx>( +fn create_coroutine_resume_function<'tcx>( tcx: TyCtxt<'tcx>, transform: TransformVisitor<'tcx>, body: &mut Body<'tcx>, @@ -1214,7 +1214,7 @@ fn create_generator_resume_function<'tcx>( ) { let can_unwind = can_unwind(tcx, body); - // Poison the generator when it unwinds + // Poison the coroutine when it unwinds if can_unwind { let source_info = SourceInfo::outermost(body.span); let poison_block = body.basic_blocks_mut().push(BasicBlockData { @@ -1253,26 +1253,26 @@ fn create_generator_resume_function<'tcx>( cases.insert(0, (UNRESUMED, START_BLOCK)); // Panic when resumed on the returned or poisoned state - let generator_kind = body.generator_kind().unwrap(); + let coroutine_kind = body.coroutine_kind().unwrap(); if can_unwind { cases.insert( 1, - (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))), + (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(coroutine_kind))), ); } if can_return { cases.insert( 1, - (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))), + (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(coroutine_kind))), ); } insert_switch(body, cases, &transform, TerminatorKind::Unreachable); - make_generator_state_argument_indirect(tcx, body); - make_generator_state_argument_pinned(tcx, body); + make_coroutine_state_argument_indirect(tcx, body); + make_coroutine_state_argument_pinned(tcx, body); // Make sure we remove dead blocks to remove // unrelated code from the drop part of the function @@ -1280,7 +1280,7 @@ fn create_generator_resume_function<'tcx>( pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None); - dump_mir(tcx, false, "generator_resume", &0, body, |_, _| Ok(())); + dump_mir(tcx, false, "coroutine_resume", &0, body, |_, _| Ok(())); } fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock { @@ -1294,7 +1294,7 @@ fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock { }; let source_info = SourceInfo::outermost(body.span); - // Create a block to destroy an unresumed generators. This can only destroy upvars. + // Create a block to destroy an unresumed coroutines. This can only destroy upvars. body.basic_blocks_mut().push(BasicBlockData { statements: Vec::new(), terminator: Some(Terminator { source_info, kind: term }), @@ -1302,7 +1302,7 @@ fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock { }) } -/// An operation that can be performed on a generator. +/// An operation that can be performed on a coroutine. #[derive(PartialEq, Copy, Clone)] enum Operation { Resume, @@ -1381,7 +1381,7 @@ fn create_cases<'tcx>( } #[instrument(level = "debug", skip(tcx), ret)] -pub(crate) fn mir_generator_witnesses<'tcx>( +pub(crate) fn mir_coroutine_witnesses<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, ) -> Option<CoroutineLayout<'tcx>> { @@ -1389,56 +1389,56 @@ pub(crate) fn mir_generator_witnesses<'tcx>( let body = body.borrow(); let body = &*body; - // The first argument is the generator type passed by value + // The first argument is the coroutine type passed by value let gen_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty; // Get the interior types and args which typeck computed let movable = match *gen_ty.kind() { ty::Coroutine(_, _, movability) => movability == hir::Movability::Movable, ty::Error(_) => return None, - _ => span_bug!(body.span, "unexpected generator type {}", gen_ty), + _ => span_bug!(body.span, "unexpected coroutine type {}", gen_ty), }; - // When first entering the generator, move the resume argument into its new local. + // When first entering the coroutine, move the resume argument into its new local. let always_live_locals = always_storage_live_locals(&body); let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable); // Extract locals which are live across suspension point into `layout` - // `remap` gives a mapping from local indices onto generator struct indices + // `remap` gives a mapping from local indices onto coroutine struct indices // `storage_liveness` tells us which locals have live storage at suspension points - let (_, generator_layout, _) = compute_layout(liveness_info, body); + let (_, coroutine_layout, _) = compute_layout(liveness_info, body); - check_suspend_tys(tcx, &generator_layout, &body); + check_suspend_tys(tcx, &coroutine_layout, &body); - Some(generator_layout) + Some(coroutine_layout) } impl<'tcx> MirPass<'tcx> for StateTransform { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let Some(yield_ty) = body.yield_ty() else { - // This only applies to generators + // This only applies to coroutines return; }; - assert!(body.generator_drop().is_none()); + assert!(body.coroutine_drop().is_none()); - // The first argument is the generator type passed by value + // The first argument is the coroutine type passed by value let gen_ty = body.local_decls.raw[1].ty; // Get the discriminant type and args which typeck computed let (discr_ty, movable) = match *gen_ty.kind() { ty::Coroutine(_, args, movability) => { - let args = args.as_generator(); + let args = args.as_coroutine(); (args.discr_ty(tcx), movability == hir::Movability::Movable) } _ => { - tcx.sess.delay_span_bug(body.span, format!("unexpected generator type {gen_ty}")); + tcx.sess.delay_span_bug(body.span, format!("unexpected coroutine type {gen_ty}")); return; } }; - let is_async_kind = matches!(body.generator_kind(), Some(CoroutineKind::Async(_))); + let is_async_kind = matches!(body.coroutine_kind(), Some(CoroutineKind::Async(_))); let (state_adt_ref, state_args) = if is_async_kind { // Compute Poll<return_ty> let poll_did = tcx.require_lang_item(LangItem::Poll, None); @@ -1465,8 +1465,8 @@ impl<'tcx> MirPass<'tcx> for StateTransform { // We also replace the resume argument and insert an `Assign`. // This is needed because the resume argument `_2` might be live across a `yield`, in which - // case there is no `Assign` to it that the transform can turn into a store to the generator - // state. After the yield the slot in the generator state would then be uninitialized. + // case there is no `Assign` to it that the transform can turn into a store to the coroutine + // state. After the yield the slot in the coroutine state would then be uninitialized. let resume_local = Local::new(2); let resume_ty = if is_async_kind { Ty::new_task_context(tcx) @@ -1475,7 +1475,7 @@ impl<'tcx> MirPass<'tcx> for StateTransform { }; let new_resume_local = replace_local(resume_local, resume_ty, body, tcx); - // When first entering the generator, move the resume argument into its new local. + // When first entering the coroutine, move the resume argument into its new local. let source_info = SourceInfo::outermost(body.span); let stmts = &mut body.basic_blocks_mut()[START_BLOCK].statements; stmts.insert( @@ -1505,15 +1505,15 @@ impl<'tcx> MirPass<'tcx> for StateTransform { } // Extract locals which are live across suspension point into `layout` - // `remap` gives a mapping from local indices onto generator struct indices + // `remap` gives a mapping from local indices onto coroutine struct indices // `storage_liveness` tells us which locals have live storage at suspension points let (remap, layout, storage_liveness) = compute_layout(liveness_info, body); let can_return = can_return(tcx, body, tcx.param_env(body.source.def_id())); - // Run the transformation which converts Places from Local to generator struct + // Run the transformation which converts Places from Local to coroutine struct // accesses for locals in `remap`. - // It also rewrites `return x` and `yield y` as writing a new generator state and returning + // It also rewrites `return x` and `yield y` as writing a new coroutine state and returning // either CoroutineState::Complete(x) and CoroutineState::Yielded(y), // or Poll::Ready(x) and Poll::Pending respectively depending on `is_async_kind`. let mut transform = TransformVisitor { @@ -1541,30 +1541,30 @@ impl<'tcx> MirPass<'tcx> for StateTransform { var.argument_index = None; } - body.generator.as_mut().unwrap().yield_ty = None; - body.generator.as_mut().unwrap().generator_layout = Some(layout); + body.coroutine.as_mut().unwrap().yield_ty = None; + body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout); - // Insert `drop(generator_struct)` which is used to drop upvars for generators in + // Insert `drop(coroutine_struct)` which is used to drop upvars for coroutines in // the unresumed state. - // This is expanded to a drop ladder in `elaborate_generator_drops`. + // This is expanded to a drop ladder in `elaborate_coroutine_drops`. let drop_clean = insert_clean_drop(body); - dump_mir(tcx, false, "generator_pre-elab", &0, body, |_, _| Ok(())); + dump_mir(tcx, false, "coroutine_pre-elab", &0, body, |_, _| Ok(())); - // Expand `drop(generator_struct)` to a drop ladder which destroys upvars. + // Expand `drop(coroutine_struct)` to a drop ladder which destroys upvars. // If any upvars are moved out of, drop elaboration will handle upvar destruction. // However we need to also elaborate the code generated by `insert_clean_drop`. - elaborate_generator_drops(tcx, body); + elaborate_coroutine_drops(tcx, body); - dump_mir(tcx, false, "generator_post-transform", &0, body, |_, _| Ok(())); + dump_mir(tcx, false, "coroutine_post-transform", &0, body, |_, _| Ok(())); - // Create a copy of our MIR and use it to create the drop shim for the generator - let drop_shim = create_generator_drop_shim(tcx, &transform, gen_ty, body, drop_clean); + // Create a copy of our MIR and use it to create the drop shim for the coroutine + let drop_shim = create_coroutine_drop_shim(tcx, &transform, gen_ty, body, drop_clean); - body.generator.as_mut().unwrap().generator_drop = Some(drop_shim); + body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim); // Create the Coroutine::resume / Future::poll function - create_generator_resume_function(tcx, transform, body, can_return); + create_coroutine_resume_function(tcx, transform, body, can_return); // Run derefer to fix Derefs that are not in the first place deref_finder(tcx, body); @@ -1572,14 +1572,14 @@ impl<'tcx> MirPass<'tcx> for StateTransform { } /// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields -/// in the generator state machine but whose storage is not marked as conflicting +/// in the coroutine state machine but whose storage is not marked as conflicting /// /// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after. /// /// This condition would arise when the assignment is the last use of `_5` but the initial /// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as -/// conflicting. Non-conflicting generator saved locals may be stored at the same location within -/// the generator state machine, which would result in ill-formed MIR: the left-hand and right-hand +/// conflicting. Non-conflicting coroutine saved locals may be stored at the same location within +/// the coroutine state machine, which would result in ill-formed MIR: the left-hand and right-hand /// sides of an assignment may not alias. This caused a miscompilation in [#73137]. /// /// [#73137]: https://github.com/rust-lang/rust/issues/73137 @@ -1624,7 +1624,7 @@ impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> { if !self.storage_conflicts.contains(lhs, rhs) { bug!( - "Assignment between generator saved locals whose storage is not \ + "Assignment between coroutine saved locals whose storage is not \ marked as conflicting: {:?}: {:?} = {:?}", location, lhs, diff --git a/compiler/rustc_mir_transform/src/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs index 9789c0b70e6..15502adfb5a 100644 --- a/compiler/rustc_mir_transform/src/dest_prop.rs +++ b/compiler/rustc_mir_transform/src/dest_prop.rs @@ -114,7 +114,7 @@ //! approach that only works for some classes of CFGs: //! - rustc now has a powerful dataflow analysis framework that can handle forwards and backwards //! analyses efficiently. -//! - Layout optimizations for generators have been added to improve code generation for +//! - Layout optimizations for coroutines have been added to improve code generation for //! async/await, which are very similar in spirit to what this optimization does. //! //! Also, rustc now has a simple NRVO pass (see `nrvo.rs`), which handles a subset of the cases that diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 60837cb4773..757b2aeca7b 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -79,10 +79,10 @@ fn inline<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool { if body.source.promoted.is_some() { return false; } - // Avoid inlining into generators, since their `optimized_mir` is used for layout computation, + // Avoid inlining into coroutines, since their `optimized_mir` is used for layout computation, // which can create a cycle, even when no attempt is made to inline the function in the other // direction. - if body.generator.is_some() { + if body.coroutine.is_some() { return false; } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index ad2803b8c51..6c0aa51795b 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -61,6 +61,7 @@ mod const_goto; mod const_prop; mod const_prop_lint; mod copy_prop; +mod coroutine; mod coverage; mod cross_crate_inline; mod ctfe_limit; @@ -77,7 +78,6 @@ mod elaborate_drops; mod errors; mod ffi_unwind_calls; mod function_item_references; -mod generator; mod gvn; pub mod inline; mod instsimplify; @@ -132,7 +132,7 @@ pub fn provide(providers: &mut Providers) { mir_promoted, mir_drops_elaborated_and_const_checked, mir_for_ctfe, - mir_generator_witnesses: generator::mir_generator_witnesses, + mir_coroutine_witnesses: coroutine::mir_coroutine_witnesses, optimized_mir, is_mir_available, is_ctfe_mir_available: |tcx, did| is_mir_available(tcx, did), @@ -376,7 +376,7 @@ fn inner_mir_for_ctfe(tcx: TyCtxt<'_>, def: LocalDefId) -> Body<'_> { /// end up missing the source MIR due to stealing happening. fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> { if let DefKind::Coroutine = tcx.def_kind(def) { - tcx.ensure_with_value().mir_generator_witnesses(def); + tcx.ensure_with_value().mir_coroutine_witnesses(def); } let mir_borrowck = tcx.mir_borrowck(def); @@ -509,7 +509,7 @@ fn run_runtime_lowering_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // `AddRetag` needs to run after `ElaborateDrops`. Otherwise it should run fairly late, // but before optimizations begin. &elaborate_box_derefs::ElaborateBoxDerefs, - &generator::StateTransform, + &coroutine::StateTransform, &add_retag::AddRetag, &Lint(const_prop_lint::ConstPropLint), ]; diff --git a/compiler/rustc_mir_transform/src/remove_zsts.rs b/compiler/rustc_mir_transform/src/remove_zsts.rs index b4784b69f7f..5aa3c3cfe4d 100644 --- a/compiler/rustc_mir_transform/src/remove_zsts.rs +++ b/compiler/rustc_mir_transform/src/remove_zsts.rs @@ -13,8 +13,8 @@ impl<'tcx> MirPass<'tcx> for RemoveZsts { } fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - // Avoid query cycles (generators require optimized MIR for layout). - if tcx.type_of(body.source.def_id()).instantiate_identity().is_generator() { + // Avoid query cycles (coroutines require optimized MIR for layout). + if tcx.type_of(body.source.def_id()).instantiate_identity().is_coroutine() { return; } let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 3cf4430824a..2400cfa21fb 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -67,10 +67,10 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<' } ty::InstanceDef::DropGlue(def_id, ty) => { - // FIXME(#91576): Drop shims for generators aren't subject to the MIR passes at the end + // FIXME(#91576): Drop shims for coroutines aren't subject to the MIR passes at the end // of this function. Is this intentional? if let Some(ty::Coroutine(gen_def_id, args, _)) = ty.map(Ty::kind) { - let body = tcx.optimized_mir(*gen_def_id).generator_drop().unwrap(); + let body = tcx.optimized_mir(*gen_def_id).coroutine_drop().unwrap(); let mut body = EarlyBinder::bind(body.clone()).instantiate(tcx, args); debug!("make_shim({:?}) = {:?}", instance, body); @@ -171,7 +171,7 @@ fn local_decls_for_sig<'tcx>( fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> { debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty); - assert!(!matches!(ty, Some(ty) if ty.is_generator())); + assert!(!matches!(ty, Some(ty) if ty.is_coroutine())); let args = if let Some(ty) = ty { tcx.mk_args(&[ty.into()]) @@ -393,7 +393,7 @@ fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) - ty::Closure(_, args) => builder.tuple_like_shim(dest, src, args.as_closure().upvar_tys()), ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()), ty::Coroutine(gen_def_id, args, hir::Movability::Movable) => { - builder.generator_shim(dest, src, *gen_def_id, args.as_generator()) + builder.coroutine_shim(dest, src, *gen_def_id, args.as_coroutine()) } _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty), }; @@ -593,7 +593,7 @@ impl<'tcx> CloneShimBuilder<'tcx> { let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, tys); } - fn generator_shim( + fn coroutine_shim( &mut self, dest: Place<'tcx>, src: Place<'tcx>, diff --git a/compiler/rustc_mir_transform/src/sroa.rs b/compiler/rustc_mir_transform/src/sroa.rs index c21b1724cbb..427cc1e1924 100644 --- a/compiler/rustc_mir_transform/src/sroa.rs +++ b/compiler/rustc_mir_transform/src/sroa.rs @@ -20,8 +20,8 @@ impl<'tcx> MirPass<'tcx> for ScalarReplacementOfAggregates { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { debug!(def_id = ?body.source.def_id()); - // Avoid query cycles (generators require optimized MIR for layout). - if tcx.type_of(body.source.def_id()).instantiate_identity().is_generator() { + // Avoid query cycles (coroutines require optimized MIR for layout). + if tcx.type_of(body.source.def_id()).instantiate_identity().is_coroutine() { return; } diff --git a/compiler/rustc_monomorphize/src/polymorphize.rs b/compiler/rustc_monomorphize/src/polymorphize.rs index 33c167930a7..a3b35eab465 100644 --- a/compiler/rustc_monomorphize/src/polymorphize.rs +++ b/compiler/rustc_monomorphize/src/polymorphize.rs @@ -227,7 +227,7 @@ struct MarkUsedGenericParams<'a, 'tcx> { impl<'a, 'tcx> MarkUsedGenericParams<'a, 'tcx> { /// Invoke `unused_generic_params` on a body contained within the current item (e.g. - /// a closure, generator or constant). + /// a closure, coroutine or constant). #[instrument(level = "debug", skip(self, def_id, args))] fn visit_child_body(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) { let instance = ty::InstanceDef::Item(def_id); @@ -249,7 +249,7 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkUsedGenericParams<'a, 'tcx> { if local == Local::from_usize(1) { let def_kind = self.tcx.def_kind(self.def_id); if matches!(def_kind, DefKind::Closure | DefKind::Coroutine) { - // Skip visiting the closure/generator that is currently being processed. This only + // Skip visiting the closure/coroutine that is currently being processed. This only // happens because the first argument to the closure is a reference to itself and // that will call `visit_args`, resulting in each generic parameter captured being // considered used by default. @@ -321,12 +321,12 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for MarkUsedGenericParams<'a, 'tcx> { match *ty.kind() { ty::Closure(def_id, args) | ty::Coroutine(def_id, args, ..) => { debug!(?def_id); - // Avoid cycle errors with generators. + // Avoid cycle errors with coroutines. if def_id == self.def_id { return ControlFlow::Continue(()); } - // Consider any generic parameters used by any closures/generators as used in the + // Consider any generic parameters used by any closures/coroutines as used in the // parent. self.visit_child_body(def_id, args); ControlFlow::Continue(()) diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 44cb90227e7..5157106f4e2 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1848,7 +1848,7 @@ impl<'a> Parser<'a> { let lo = self.prev_token.span; let kind = ExprKind::Yield(self.parse_expr_opt()?); let span = lo.to(self.prev_token.span); - self.sess.gated_spans.gate(sym::generators, span); + self.sess.gated_spans.gate(sym::coroutines, span); let expr = self.mk_expr(span, kind); self.maybe_recover_from_bad_qpath(expr) } diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index 7e837243918..2aec4ea7ef1 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -149,7 +149,7 @@ impl<'tcx> LanguageItemCollector<'tcx> { // Now check whether the lang_item has the expected number of generic // arguments. Generally speaking, binary and indexing operations have // one (for the RHS/index), unary operations have none, the closure - // traits have one for the argument list, generators have one for the + // traits have one for the argument list, coroutines have one for the // resume argument, and ordering/equality relations have one for the RHS // Some other types like Box and various functions like drop_in_place // have minimum requirements. diff --git a/compiler/rustc_session/src/code_stats.rs b/compiler/rustc_session/src/code_stats.rs index 0caa4453993..f792b8f2cdd 100644 --- a/compiler/rustc_session/src/code_stats.rs +++ b/compiler/rustc_session/src/code_stats.rs @@ -106,7 +106,7 @@ impl CodeStats { // used here so that source code order is preserved for all variants // that have the same size. // Except for Coroutines, whose variants are already sorted according to - // their yield points in `variant_info_for_generator`. + // their yield points in `variant_info_for_coroutine`. if kind != DataTypeKind::Coroutine { variants.sort_by_key(|info| cmp::Reverse(info.size)); } diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs index 7feeb63c23a..61227e5d38f 100644 --- a/compiler/rustc_smir/src/rustc_internal/mod.rs +++ b/compiler/rustc_smir/src/rustc_internal/mod.rs @@ -59,7 +59,7 @@ impl<'tcx> Tables<'tcx> { stable_mir::ty::ClosureDef(self.create_def_id(did)) } - pub fn generator_def(&mut self, did: DefId) -> stable_mir::ty::CoroutineDef { + pub fn coroutine_def(&mut self, did: DefId) -> stable_mir::ty::CoroutineDef { stable_mir::ty::CoroutineDef(self.create_def_id(did)) } diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index cb5f50e1cfc..0fc25aac3de 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -768,11 +768,11 @@ impl<'tcx> Stable<'tcx> for mir::AssertMessage<'tcx> { AssertKind::RemainderByZero(op) => { stable_mir::mir::AssertMessage::RemainderByZero(op.stable(tables)) } - AssertKind::ResumedAfterReturn(generator) => { - stable_mir::mir::AssertMessage::ResumedAfterReturn(generator.stable(tables)) + AssertKind::ResumedAfterReturn(coroutine) => { + stable_mir::mir::AssertMessage::ResumedAfterReturn(coroutine.stable(tables)) } - AssertKind::ResumedAfterPanic(generator) => { - stable_mir::mir::AssertMessage::ResumedAfterPanic(generator.stable(tables)) + AssertKind::ResumedAfterPanic(coroutine) => { + stable_mir::mir::AssertMessage::ResumedAfterPanic(coroutine.stable(tables)) } AssertKind::MisalignedPointerDereference { required, found } => { stable_mir::mir::AssertMessage::MisalignedPointerDereference { @@ -851,7 +851,7 @@ impl<'tcx> Stable<'tcx> for mir::AggregateKind<'tcx> { } mir::AggregateKind::Coroutine(def_id, generic_arg, movability) => { stable_mir::mir::AggregateKind::Coroutine( - tables.generator_def(*def_id), + tables.coroutine_def(*def_id), generic_arg.stable(tables), movability.stable(tables), ) @@ -1232,7 +1232,7 @@ impl<'tcx> Stable<'tcx> for Ty<'tcx> { generic_args.stable(tables), )), ty::Coroutine(def_id, generic_args, movability) => TyKind::RigidTy(RigidTy::Coroutine( - tables.generator_def(*def_id), + tables.coroutine_def(*def_id), generic_args.stable(tables), movability.stable(tables), )), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index be8c65862dc..bfa8d7c7d2d 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -591,6 +591,10 @@ symbols! { core_panic_2015_macro, core_panic_2021_macro, core_panic_macro, + coroutine, + coroutine_clone, + coroutine_state, + coroutines, cosf32, cosf64, count, @@ -815,10 +819,6 @@ symbols! { ge, gen_future, gen_kill, - generator, - generator_clone, - generator_state, - generators, generic_arg_infer, generic_assert, generic_associated_types, diff --git a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs index fc186462a26..5ce188488ce 100644 --- a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs +++ b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs @@ -648,7 +648,7 @@ fn encode_ty<'tcx>( // Encode parent args only s.push_str(&encode_args( tcx, - tcx.mk_args(args.as_generator().parent_args()), + tcx.mk_args(args.as_coroutine().parent_args()), dict, options, )); @@ -893,7 +893,7 @@ fn transform_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, options: TransformTyOptio } ty::Coroutine(def_id, args, movability) => { - ty = Ty::new_generator(tcx, *def_id, transform_args(tcx, args, options), *movability); + ty = Ty::new_coroutine(tcx, *def_id, transform_args(tcx, args, options), *movability); } ty::Ref(region, ty0, ..) => { diff --git a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs index 68f872308a7..0c214ca8753 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs @@ -191,18 +191,18 @@ pub(super) trait GoalKind<'tcx>: goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; - /// A generator (that comes from an `async` desugaring) is known to implement - /// `Future<Output = O>`, where `O` is given by the generator's return type + /// A coroutine (that comes from an `async` desugaring) is known to implement + /// `Future<Output = O>`, where `O` is given by the coroutine's return type /// that was computed during type-checking. fn consider_builtin_future_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; - /// A generator (that doesn't come from an `async` desugaring) is known to + /// A coroutine (that doesn't come from an `async` desugaring) is known to /// implement `Coroutine<R, Yield = Y, Return = O>`, given the resume, yield, - /// and return types of the generator computed during type-checking. - fn consider_builtin_generator_candidate( + /// and return types of the coroutine computed during type-checking. + fn consider_builtin_coroutine_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; @@ -467,7 +467,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { ty::Alias(_, _) | ty::Placeholder(..) | ty::Error(_) => (), // FIXME: These should ideally not exist as a self type. It would be nice for - // the builtin auto trait impls of generators to instead directly recurse + // the builtin auto trait impls of coroutines to instead directly recurse // into the witness. ty::CoroutineWitness(..) => (), @@ -553,7 +553,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { } else if lang_items.future_trait() == Some(trait_def_id) { G::consider_builtin_future_candidate(self, goal) } else if lang_items.gen_trait() == Some(trait_def_id) { - G::consider_builtin_generator_candidate(self, goal) + G::consider_builtin_coroutine_candidate(self, goal) } else if lang_items.discriminant_kind_trait() == Some(trait_def_id) { G::consider_builtin_discriminant_kind_candidate(self, goal) } else if lang_items.destruct_trait() == Some(trait_def_id) { diff --git a/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs b/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs index afe1424daca..d655a4106b8 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs @@ -12,7 +12,7 @@ use crate::solve::EvalCtxt; // Calculates the constituent types of a type for `auto trait` purposes. // -// For types with an "existential" binder, i.e. generator witnesses, we also +// For types with an "existential" binder, i.e. coroutine witnesses, we also // instantiate the binder with placeholders eagerly. pub(in crate::solve) fn instantiate_constituent_tys_for_auto_trait<'tcx>( ecx: &EvalCtxt<'_, 'tcx>, @@ -57,13 +57,13 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_auto_trait<'tcx>( ty::Closure(_, ref args) => Ok(vec![args.as_closure().tupled_upvars_ty()]), ty::Coroutine(_, ref args, _) => { - let generator_args = args.as_generator(); - Ok(vec![generator_args.tupled_upvars_ty(), generator_args.witness()]) + let coroutine_args = args.as_coroutine(); + Ok(vec![coroutine_args.tupled_upvars_ty(), coroutine_args.witness()]) } ty::CoroutineWitness(def_id, args) => Ok(ecx .tcx() - .generator_hidden_types(def_id) + .coroutine_hidden_types(def_id) .map(|bty| { ecx.instantiate_binder_with_placeholders(replace_erased_lifetimes_with_bound_vars( tcx, @@ -192,9 +192,9 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( ty::Closure(_, args) => Ok(vec![args.as_closure().tupled_upvars_ty()]), ty::Coroutine(_, args, Movability::Movable) => { - if ecx.tcx().features().generator_clone { - let generator = args.as_generator(); - Ok(vec![generator.tupled_upvars_ty(), generator.witness()]) + if ecx.tcx().features().coroutine_clone { + let coroutine = args.as_coroutine(); + Ok(vec![coroutine.tupled_upvars_ty(), coroutine.witness()]) } else { Err(NoSolution) } @@ -202,7 +202,7 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( ty::CoroutineWitness(def_id, args) => Ok(ecx .tcx() - .generator_hidden_types(def_id) + .coroutine_hidden_types(def_id) .map(|bty| { ecx.instantiate_binder_with_placeholders(replace_erased_lifetimes_with_bound_vars( ecx.tcx(), diff --git a/compiler/rustc_trait_selection/src/solve/project_goals/mod.rs b/compiler/rustc_trait_selection/src/solve/project_goals/mod.rs index d5f22a2e5f2..4950a444ffb 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals/mod.rs @@ -465,11 +465,11 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { // Coroutines are not futures unless they come from `async` desugaring let tcx = ecx.tcx(); - if !tcx.generator_is_async(def_id) { + if !tcx.coroutine_is_async(def_id) { return Err(NoSolution); } - let term = args.as_generator().return_ty().into(); + let term = args.as_coroutine().return_ty().into(); Self::consider_implied_clause( ecx, @@ -480,12 +480,12 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { } .to_predicate(tcx), // Technically, we need to check that the future type is Sized, - // but that's already proven by the generator being WF. + // but that's already proven by the coroutine being WF. [], ) } - fn consider_builtin_generator_candidate( + fn consider_builtin_coroutine_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx> { @@ -494,19 +494,19 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { return Err(NoSolution); }; - // `async`-desugared generators do not implement the generator trait + // `async`-desugared coroutines do not implement the coroutine trait let tcx = ecx.tcx(); - if tcx.generator_is_async(def_id) { + if tcx.coroutine_is_async(def_id) { return Err(NoSolution); } - let generator = args.as_generator(); + let coroutine = args.as_coroutine(); let name = tcx.associated_item(goal.predicate.def_id()).name; let term = if name == sym::Return { - generator.return_ty().into() + coroutine.return_ty().into() } else if name == sym::Yield { - generator.yield_ty().into() + coroutine.yield_ty().into() } else { bug!("unexpected associated item `<{self_ty} as Coroutine>::{name}`") }; @@ -518,13 +518,13 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { projection_ty: ty::AliasTy::new( ecx.tcx(), goal.predicate.def_id(), - [self_ty, generator.resume_ty()], + [self_ty, coroutine.resume_ty()], ), term, } .to_predicate(tcx), // Technically, we need to check that the future type is Sized, - // but that's already proven by the generator being WF. + // but that's already proven by the coroutine being WF. [], ) } diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index 3aac24f82e7..fa91a125b6a 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -325,17 +325,17 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { // Coroutines are not futures unless they come from `async` desugaring let tcx = ecx.tcx(); - if !tcx.generator_is_async(def_id) { + if !tcx.coroutine_is_async(def_id) { return Err(NoSolution); } - // Async generator unconditionally implement `Future` + // Async coroutine unconditionally implement `Future` // Technically, we need to check that the future output type is Sized, - // but that's already proven by the generator being WF. + // but that's already proven by the coroutine being WF. ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) } - fn consider_builtin_generator_candidate( + fn consider_builtin_coroutine_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx> { @@ -348,20 +348,20 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { return Err(NoSolution); }; - // `async`-desugared generators do not implement the generator trait + // `async`-desugared coroutines do not implement the coroutine trait let tcx = ecx.tcx(); - if tcx.generator_is_async(def_id) { + if tcx.coroutine_is_async(def_id) { return Err(NoSolution); } - let generator = args.as_generator(); + let coroutine = args.as_coroutine(); Self::consider_implied_clause( ecx, goal, - ty::TraitRef::new(tcx, goal.predicate.def_id(), [self_ty, generator.resume_ty()]) + ty::TraitRef::new(tcx, goal.predicate.def_id(), [self_ty, coroutine.resume_ty()]) .to_predicate(tcx), - // Technically, we need to check that the generator types are Sized, - // but that's already proven by the generator being WF. + // Technically, we need to check that the coroutine types are Sized, + // but that's already proven by the coroutine being WF. [], ) } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index 9c9b78f4152..016c44c20f6 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -102,7 +102,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let node = hir.find(hir_id)?; match &node { hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. }) => { - self.describe_generator(*body_id).or_else(|| { + self.describe_coroutine(*body_id).or_else(|| { Some(match sig.header { hir::FnHeader { asyncness: hir::IsAsync::Async(_), .. } => { "an async function" @@ -114,11 +114,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)), .. - }) => self.describe_generator(*body_id).or_else(|| Some("a trait method")), + }) => self.describe_coroutine(*body_id).or_else(|| Some("a trait method")), hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(sig, body_id), .. - }) => self.describe_generator(*body_id).or_else(|| { + }) => self.describe_coroutine(*body_id).or_else(|| { Some(match sig.header { hir::FnHeader { asyncness: hir::IsAsync::Async(_), .. } => "an async method", _ => "a method", @@ -127,7 +127,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(hir::Closure { body, movability, .. }), .. - }) => self.describe_generator(*body).or_else(|| { + }) => self.describe_coroutine(*body).or_else(|| { Some(if movability.is_some() { "an async closure" } else { "a closure" }) }), hir::Node::Expr(hir::Expr { .. }) => { diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index ab965357cf2..6f9288694a3 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -54,25 +54,25 @@ pub enum CoroutineInteriorOrUpvar { Upvar(Span), } -// This type provides a uniform interface to retrieve data on generators, whether it originated from +// This type provides a uniform interface to retrieve data on coroutines, whether it originated from // the local crate being compiled or from a foreign crate. #[derive(Debug)] struct CoroutineData<'tcx, 'a>(&'a TypeckResults<'tcx>); impl<'tcx, 'a> CoroutineData<'tcx, 'a> { - /// Try to get information about variables captured by the generator that matches a type we are + /// Try to get information about variables captured by the coroutine that matches a type we are /// looking for with `ty_matches` function. We uses it to find upvar which causes a failure to /// meet an obligation fn try_get_upvar_span<F>( &self, infer_context: &InferCtxt<'tcx>, - generator_did: DefId, + coroutine_did: DefId, ty_matches: F, ) -> Option<CoroutineInteriorOrUpvar> where F: Fn(ty::Binder<'tcx, Ty<'tcx>>) -> bool, { - infer_context.tcx.upvars_mentioned(generator_did).and_then(|upvars| { + infer_context.tcx.upvars_mentioned(coroutine_did).and_then(|upvars| { upvars.iter().find_map(|(upvar_id, upvar)| { let upvar_ty = self.0.node_type(*upvar_id); let upvar_ty = infer_context.resolve_vars_if_possible(upvar_ty); @@ -246,7 +246,7 @@ pub trait TypeErrCtxtExt<'tcx> { err: &mut Diagnostic, interior_or_upvar_span: CoroutineInteriorOrUpvar, is_async: bool, - outer_generator: Option<DefId>, + outer_coroutine: Option<DefId>, trait_pred: ty::TraitPredicate<'tcx>, target_ty: Ty<'tcx>, obligation: &PredicateObligation<'tcx>, @@ -1982,7 +1982,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let argument_kind = match expected.skip_binder().self_ty().kind() { ty::Closure(..) => "closure", - ty::Coroutine(..) => "generator", + ty::Coroutine(..) => "coroutine", _ => "function", }; let mut err = struct_span_err!( @@ -2144,33 +2144,33 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let hir = self.tcx.hir(); // Attempt to detect an async-await error by looking at the obligation causes, looking - // for a generator to be present. + // for a coroutine to be present. // // When a future does not implement a trait because of a captured type in one of the - // generators somewhere in the call stack, then the result is a chain of obligations. + // coroutines somewhere in the call stack, then the result is a chain of obligations. // // Given an `async fn` A that calls an `async fn` B which captures a non-send type and that // future is passed as an argument to a function C which requires a `Send` type, then the // chain looks something like this: // - // - `BuiltinDerivedObligation` with a generator witness (B) - // - `BuiltinDerivedObligation` with a generator (B) + // - `BuiltinDerivedObligation` with a coroutine witness (B) + // - `BuiltinDerivedObligation` with a coroutine (B) // - `BuiltinDerivedObligation` with `impl std::future::Future` (B) - // - `BuiltinDerivedObligation` with a generator witness (A) - // - `BuiltinDerivedObligation` with a generator (A) + // - `BuiltinDerivedObligation` with a coroutine witness (A) + // - `BuiltinDerivedObligation` with a coroutine (A) // - `BuiltinDerivedObligation` with `impl std::future::Future` (A) // - `BindingObligation` with `impl_send` (Send requirement) // - // The first obligation in the chain is the most useful and has the generator that captured - // the type. The last generator (`outer_generator` below) has information about where the - // bound was introduced. At least one generator should be present for this diagnostic to be + // The first obligation in the chain is the most useful and has the coroutine that captured + // the type. The last coroutine (`outer_coroutine` below) has information about where the + // bound was introduced. At least one coroutine should be present for this diagnostic to be // modified. let (mut trait_ref, mut target_ty) = match obligation.predicate.kind().skip_binder() { ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => (Some(p), Some(p.self_ty())), _ => (None, None), }; - let mut generator = None; - let mut outer_generator = None; + let mut coroutine = None; + let mut outer_coroutine = None; let mut next_code = Some(obligation.cause.code()); let mut seen_upvar_tys_infer_tuple = false; @@ -2191,17 +2191,17 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { match *ty.kind() { ty::Coroutine(did, ..) | ty::CoroutineWitness(did, _) => { - generator = generator.or(Some(did)); - outer_generator = Some(did); + coroutine = coroutine.or(Some(did)); + outer_coroutine = Some(did); } ty::Tuple(_) if !seen_upvar_tys_infer_tuple => { // By introducing a tuple of upvar types into the chain of obligations - // of a generator, the first non-generator item is now the tuple itself, + // of a coroutine, the first non-coroutine item is now the tuple itself, // we shall ignore this. seen_upvar_tys_infer_tuple = true; } - _ if generator.is_none() => { + _ if coroutine.is_none() => { trait_ref = Some(cause.derived.parent_trait_pred.skip_binder()); target_ty = Some(ty); } @@ -2220,17 +2220,17 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { match *ty.kind() { ty::Coroutine(did, ..) | ty::CoroutineWitness(did, ..) => { - generator = generator.or(Some(did)); - outer_generator = Some(did); + coroutine = coroutine.or(Some(did)); + outer_coroutine = Some(did); } ty::Tuple(_) if !seen_upvar_tys_infer_tuple => { // By introducing a tuple of upvar types into the chain of obligations - // of a generator, the first non-generator item is now the tuple itself, + // of a coroutine, the first non-coroutine item is now the tuple itself, // we shall ignore this. seen_upvar_tys_infer_tuple = true; } - _ if generator.is_none() => { + _ if coroutine.is_none() => { trait_ref = Some(derived_obligation.parent_trait_pred.skip_binder()); target_ty = Some(ty); } @@ -2243,48 +2243,48 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } } - // Only continue if a generator was found. - debug!(?generator, ?trait_ref, ?target_ty); - let (Some(generator_did), Some(trait_ref), Some(target_ty)) = - (generator, trait_ref, target_ty) + // Only continue if a coroutine was found. + debug!(?coroutine, ?trait_ref, ?target_ty); + let (Some(coroutine_did), Some(trait_ref), Some(target_ty)) = + (coroutine, trait_ref, target_ty) else { return false; }; - let span = self.tcx.def_span(generator_did); + let span = self.tcx.def_span(coroutine_did); - let generator_did_root = self.tcx.typeck_root_def_id(generator_did); + let coroutine_did_root = self.tcx.typeck_root_def_id(coroutine_did); debug!( - ?generator_did, - ?generator_did_root, + ?coroutine_did, + ?coroutine_did_root, typeck_results.hir_owner = ?self.typeck_results.as_ref().map(|t| t.hir_owner), ?span, ); - let generator_body = generator_did + let coroutine_body = coroutine_did .as_local() .and_then(|def_id| hir.maybe_body_owned_by(def_id)) .map(|body_id| hir.body(body_id)); let mut visitor = AwaitsVisitor::default(); - if let Some(body) = generator_body { + if let Some(body) = coroutine_body { visitor.visit_body(body); } debug!(awaits = ?visitor.awaits); - // Look for a type inside the generator interior that matches the target type to get + // Look for a type inside the coroutine interior that matches the target type to get // a span. let target_ty_erased = self.tcx.erase_regions(target_ty); let ty_matches = |ty| -> bool { // Careful: the regions for types that appear in the - // generator interior are not generally known, so we + // coroutine interior are not generally known, so we // want to erase them when comparing (and anyway, // `Send` and other bounds are generally unaffected by // the choice of region). When erasing regions, we // also have to erase late-bound regions. This is - // because the types that appear in the generator + // because the types that appear in the coroutine // interior generally contain "bound regions" to // represent regions that are part of the suspended - // generator frame. Bound regions are preserved by + // coroutine frame. Bound regions are preserved by // `erase_regions` and so we must also call // `erase_late_bound_regions`. let ty_erased = self.tcx.erase_late_bound_regions(ty); @@ -2294,41 +2294,41 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { eq }; - // Get the typeck results from the infcx if the generator is the function we are currently + // Get the typeck results from the infcx if the coroutine is the function we are currently // type-checking; otherwise, get them by performing a query. This is needed to avoid - // cycles. If we can't use resolved types because the generator comes from another crate, + // cycles. If we can't use resolved types because the coroutine comes from another crate, // we still provide a targeted error but without all the relevant spans. - let generator_data = match &self.typeck_results { - Some(t) if t.hir_owner.to_def_id() == generator_did_root => CoroutineData(&t), - _ if generator_did.is_local() => { - CoroutineData(self.tcx.typeck(generator_did.expect_local())) + let coroutine_data = match &self.typeck_results { + Some(t) if t.hir_owner.to_def_id() == coroutine_did_root => CoroutineData(&t), + _ if coroutine_did.is_local() => { + CoroutineData(self.tcx.typeck(coroutine_did.expect_local())) } _ => return false, }; - let generator_within_in_progress_typeck = match &self.typeck_results { - Some(t) => t.hir_owner.to_def_id() == generator_did_root, + let coroutine_within_in_progress_typeck = match &self.typeck_results { + Some(t) => t.hir_owner.to_def_id() == coroutine_did_root, _ => false, }; let mut interior_or_upvar_span = None; - let from_awaited_ty = generator_data.get_from_await_ty(visitor, hir, ty_matches); + let from_awaited_ty = coroutine_data.get_from_await_ty(visitor, hir, ty_matches); debug!(?from_awaited_ty); // Avoid disclosing internal information to downstream crates. - if generator_did.is_local() + if coroutine_did.is_local() // Try to avoid cycles. - && !generator_within_in_progress_typeck - && let Some(generator_info) = self.tcx.mir_generator_witnesses(generator_did) + && !coroutine_within_in_progress_typeck + && let Some(coroutine_info) = self.tcx.mir_coroutine_witnesses(coroutine_did) { - debug!(?generator_info); + debug!(?coroutine_info); 'find_source: for (variant, source_info) in - generator_info.variant_fields.iter().zip(&generator_info.variant_source_info) + coroutine_info.variant_fields.iter().zip(&coroutine_info.variant_source_info) { debug!(?variant); for &local in variant { - let decl = &generator_info.field_tys[local]; + let decl = &coroutine_info.field_tys[local]; debug!(?decl); if ty_matches(ty::Binder::dummy(decl.ty)) && !decl.ignore_for_traits { interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior( @@ -2343,21 +2343,21 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if interior_or_upvar_span.is_none() { interior_or_upvar_span = - generator_data.try_get_upvar_span(&self, generator_did, ty_matches); + coroutine_data.try_get_upvar_span(&self, coroutine_did, ty_matches); } - if interior_or_upvar_span.is_none() && !generator_did.is_local() { + if interior_or_upvar_span.is_none() && !coroutine_did.is_local() { interior_or_upvar_span = Some(CoroutineInteriorOrUpvar::Interior(span, None)); } debug!(?interior_or_upvar_span); if let Some(interior_or_upvar_span) = interior_or_upvar_span { - let is_async = self.tcx.generator_is_async(generator_did); + let is_async = self.tcx.coroutine_is_async(coroutine_did); self.note_obligation_cause_for_async_await( err, interior_or_upvar_span, is_async, - outer_generator, + outer_coroutine, trait_ref, target_ty, obligation, @@ -2377,7 +2377,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err: &mut Diagnostic, interior_or_upvar_span: CoroutineInteriorOrUpvar, is_async: bool, - outer_generator: Option<DefId>, + outer_coroutine: Option<DefId>, trait_pred: ty::TraitPredicate<'tcx>, target_ty: Ty<'tcx>, obligation: &PredicateObligation<'tcx>, @@ -2387,7 +2387,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let (await_or_yield, an_await_or_yield) = if is_async { ("await", "an await") } else { ("yield", "a yield") }; - let future_or_generator = if is_async { "future" } else { "generator" }; + let future_or_coroutine = if is_async { "future" } else { "coroutine" }; // Special case the primary error message when send or sync is the trait that was // not implemented. @@ -2400,19 +2400,19 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.clear_code(); err.set_primary_message(format!( - "{future_or_generator} cannot be {trait_verb} between threads safely" + "{future_or_coroutine} cannot be {trait_verb} between threads safely" )); let original_span = err.span.primary_span().unwrap(); let mut span = MultiSpan::from_span(original_span); - let message = outer_generator - .and_then(|generator_did| { - Some(match self.tcx.generator_kind(generator_did).unwrap() { - CoroutineKind::Gen => format!("generator is not {trait_name}"), + let message = outer_coroutine + .and_then(|coroutine_did| { + Some(match self.tcx.coroutine_kind(coroutine_did).unwrap() { + CoroutineKind::Gen => format!("coroutine is not {trait_name}"), CoroutineKind::Async(AsyncCoroutineKind::Fn) => self .tcx - .parent(generator_did) + .parent(coroutine_did) .as_local() .map(|parent_did| hir.local_def_id_to_hir_id(parent_did)) .and_then(|parent_hir_id| hir.opt_name(parent_hir_id)) @@ -2427,7 +2427,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } }) }) - .unwrap_or_else(|| format!("{future_or_generator} is not {trait_name}")); + .unwrap_or_else(|| format!("{future_or_coroutine} is not {trait_name}")); span.push_span_label(original_span, message); err.set_span(span); @@ -2471,7 +2471,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ); err.span_note( span, - format!("{future_or_generator} {trait_explanation} as this value is used across {an_await_or_yield}"), + format!("{future_or_coroutine} {trait_explanation} as this value is used across {an_await_or_yield}"), ); }; match interior_or_upvar_span { @@ -2810,7 +2810,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.note("the return type of a function must have a statically known size"); } ObligationCauseCode::SizedYieldType => { - err.note("the yield type of a generator must have a statically known size"); + err.note("the yield type of a coroutine must have a statically known size"); } ObligationCauseCode::AssignmentLhsSized => { err.note("the left-hand-side of an assignment must have a statically known size"); @@ -2880,8 +2880,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.span_label(span, "this closure captures all values by move"); } } - ObligationCauseCode::SizedCoroutineInterior(generator_def_id) => { - let what = match self.tcx.generator_kind(generator_def_id) { + ObligationCauseCode::SizedCoroutineInterior(coroutine_def_id) => { + let what = match self.tcx.coroutine_kind(coroutine_def_id) { None | Some(hir::CoroutineKind::Gen) => "yield", Some(hir::CoroutineKind::Async(..)) => "await", }; @@ -2945,7 +2945,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if is_future && obligated_types.last().is_some_and(|ty| match ty.kind() { ty::Coroutine(last_def_id, ..) => { - tcx.generator_is_async(*last_def_id) + tcx.coroutine_is_async(*last_def_id) } _ => false, }) @@ -2962,7 +2962,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // FIXME: only print types which don't meet the trait requirement let mut msg = "required because it captures the following types: ".to_owned(); - for bty in tcx.generator_hidden_types(*def_id) { + for bty in tcx.coroutine_hidden_types(*def_id) { let ty = bty.instantiate(tcx, args); write!(msg, "`{ty}`, ").unwrap(); } @@ -2971,8 +2971,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ty::Coroutine(def_id, _, _) => { let sp = self.tcx.def_span(def_id); - // Special-case this to say "async block" instead of `[static generator]`. - let kind = tcx.generator_kind(def_id).unwrap().descr(); + // Special-case this to say "async block" instead of `[static coroutine]`. + let kind = tcx.coroutine_kind(def_id).unwrap().descr(); err.span_note( sp, with_forced_trimmed_paths!(format!( @@ -3271,7 +3271,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ) { if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) { let body = self.tcx.hir().body(body_id); - if let Some(hir::CoroutineKind::Async(_)) = body.generator_kind { + if let Some(hir::CoroutineKind::Async(_)) = body.coroutine_kind { let future_trait = self.tcx.require_lang_item(LangItem::Future, None); let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); @@ -4332,7 +4332,7 @@ impl<'v> Visitor<'v> for ReturnsVisitor<'v> { fn visit_body(&mut self, body: &'v hir::Body<'v>) { assert!(!self.in_block_tail); - if body.generator_kind().is_none() { + if body.coroutine_kind().is_none() { if let hir::ExprKind::Block(block, None) = body.value.kind { if block.expr.is_some() { self.in_block_tail = true; diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs index fe182c1fe09..83d7b502216 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs @@ -1036,7 +1036,7 @@ pub(super) trait InferCtxtPrivExt<'tcx> { ignoring_lifetimes: bool, ) -> Option<CandidateSimilarity>; - fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>; + fn describe_coroutine(&self, body_id: hir::BodyId) -> Option<&'static str>; fn find_similar_impl_candidates( &self, @@ -1613,9 +1613,9 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } } - fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> { - self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind { - hir::CoroutineKind::Gen => "a generator", + fn describe_coroutine(&self, body_id: hir::BodyId) -> Option<&'static str> { + self.tcx.hir().body(body_id).coroutine_kind.map(|gen_kind| match gen_kind { + hir::CoroutineKind::Gen => "a coroutine", hir::CoroutineKind::Async(hir::AsyncCoroutineKind::Block) => "an async block", hir::CoroutineKind::Async(hir::AsyncCoroutineKind::Fn) => "an async function", hir::CoroutineKind::Async(hir::AsyncCoroutineKind::Closure) => "an async closure", diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 56a005297a8..c3f56ae2756 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -2003,7 +2003,7 @@ fn confirm_select_candidate<'cx, 'tcx>( let trait_def_id = obligation.predicate.trait_def_id(selcx.tcx()); let lang_items = selcx.tcx().lang_items(); if lang_items.gen_trait() == Some(trait_def_id) { - confirm_generator_candidate(selcx, obligation, data) + confirm_coroutine_candidate(selcx, obligation, data) } else if lang_items.future_trait() == Some(trait_def_id) { confirm_future_candidate(selcx, obligation, data) } else if selcx.tcx().fn_trait_kind_from_def_id(trait_def_id).is_some() { @@ -2030,7 +2030,7 @@ fn confirm_select_candidate<'cx, 'tcx>( } } -fn confirm_generator_candidate<'cx, 'tcx>( +fn confirm_coroutine_candidate<'cx, 'tcx>( selcx: &mut SelectionContext<'cx, 'tcx>, obligation: &ProjectionTyObligation<'tcx>, nested: Vec<PredicateObligation<'tcx>>, @@ -2040,7 +2040,7 @@ fn confirm_generator_candidate<'cx, 'tcx>( else { unreachable!() }; - let gen_sig = args.as_generator().poly_sig(); + let gen_sig = args.as_coroutine().poly_sig(); let Normalized { value: gen_sig, obligations } = normalize_with_depth( selcx, obligation.param_env, @@ -2049,13 +2049,13 @@ fn confirm_generator_candidate<'cx, 'tcx>( gen_sig, ); - debug!(?obligation, ?gen_sig, ?obligations, "confirm_generator_candidate"); + debug!(?obligation, ?gen_sig, ?obligations, "confirm_coroutine_candidate"); let tcx = selcx.tcx(); let gen_def_id = tcx.require_lang_item(LangItem::Coroutine, None); - let predicate = super::util::generator_trait_ref_and_outputs( + let predicate = super::util::coroutine_trait_ref_and_outputs( tcx, gen_def_id, obligation.predicate.self_ty(), @@ -2092,7 +2092,7 @@ fn confirm_future_candidate<'cx, 'tcx>( else { unreachable!() }; - let gen_sig = args.as_generator().poly_sig(); + let gen_sig = args.as_coroutine().poly_sig(); let Normalized { value: gen_sig, obligations } = normalize_with_depth( selcx, obligation.param_env, diff --git a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs index 2b39b1e1f90..0783eec6fe8 100644 --- a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs @@ -257,20 +257,20 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( ty::Coroutine(_, args, _movability) => { // rust-lang/rust#49918: types can be constructed, stored - // in the interior, and sit idle when generator yields + // in the interior, and sit idle when coroutine yields // (and is subsequently dropped). // // It would be nice to descend into interior of a - // generator to determine what effects dropping it might + // coroutine to determine what effects dropping it might // have (by looking at any drop effects associated with // its interior). // // However, the interior's representation uses things like // CoroutineWitness that explicitly assume they are not // traversed in such a manner. So instead, we will - // simplify things for now by treating all generators as + // simplify things for now by treating all coroutines as // if they were like trait objects, where its upvars must - // all be alive for the generator's (potential) + // all be alive for the coroutine's (potential) // destructor. // // In particular, skipping over `_interior` is safe @@ -279,20 +279,20 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( // derived from lifetimes attached to the upvars and resume // argument, and we *do* incorporate those here. - if !args.as_generator().is_valid() { + if !args.as_coroutine().is_valid() { // By the time this code runs, all type variables ought to // be fully resolved. tcx.sess.delay_span_bug( span, - format!("upvar_tys for generator not found. Expected capture information for generator {ty}",), + format!("upvar_tys for coroutine not found. Expected capture information for coroutine {ty}",), ); return Err(NoSolution); } constraints .outlives - .extend(args.as_generator().upvar_tys().iter().map(ty::GenericArg::from)); - constraints.outlives.push(args.as_generator().resume_ty().into()); + .extend(args.as_coroutine().upvar_tys().iter().map(ty::GenericArg::from)); + constraints.outlives.push(args.as_coroutine().resume_ty().into()); } ty::Adt(def, args) => { diff --git a/compiler/rustc_trait_selection/src/traits/query/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/normalize.rs index f785211c548..349741a698c 100644 --- a/compiler/rustc_trait_selection/src/traits/query/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/normalize.rs @@ -231,7 +231,7 @@ impl<'cx, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for QueryNormalizer<'cx, 'tcx> let args = data.args.try_fold_with(self)?; let recursion_limit = self.interner().recursion_limit(); if !recursion_limit.value_within_limit(self.anon_depth) { - // A closure or generator may have itself as in its upvars. + // A closure or coroutine may have itself as in its upvars. // This should be checked handled by the recursion check for opaque // types, but we may end up here before that check can happen. // In that case, we delay a bug to mark the trip, and continue without diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 4059fb5004e..ee50a36be55 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -111,7 +111,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } if lang_items.gen_trait() == Some(def_id) { - self.assemble_generator_candidates(obligation, &mut candidates); + self.assemble_coroutine_candidates(obligation, &mut candidates); } else if lang_items.future_trait() == Some(def_id) { self.assemble_future_candidates(obligation, &mut candidates); } @@ -201,25 +201,25 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { Ok(()) } - fn assemble_generator_candidates( + fn assemble_coroutine_candidates( &mut self, obligation: &PolyTraitObligation<'tcx>, candidates: &mut SelectionCandidateSet<'tcx>, ) { - // Okay to skip binder because the args on generator types never + // Okay to skip binder because the args on coroutine types never // touch bound regions, they just capture the in-scope // type/region parameters. let self_ty = obligation.self_ty().skip_binder(); match self_ty.kind() { - // async constructs get lowered to a special kind of generator that + // async constructs get lowered to a special kind of coroutine that // should *not* `impl Coroutine`. - ty::Coroutine(did, ..) if !self.tcx().generator_is_async(*did) => { - debug!(?self_ty, ?obligation, "assemble_generator_candidates",); + ty::Coroutine(did, ..) if !self.tcx().coroutine_is_async(*did) => { + debug!(?self_ty, ?obligation, "assemble_coroutine_candidates",); candidates.vec.push(CoroutineCandidate); } ty::Infer(ty::TyVar(_)) => { - debug!("assemble_generator_candidates: ambiguous self-type"); + debug!("assemble_coroutine_candidates: ambiguous self-type"); candidates.ambiguous = true; } _ => {} @@ -233,9 +233,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ) { let self_ty = obligation.self_ty().skip_binder(); if let ty::Coroutine(did, ..) = self_ty.kind() { - // async constructs get lowered to a special kind of generator that + // async constructs get lowered to a special kind of coroutine that // should directly `impl Future`. - if self.tcx().generator_is_async(*did) { + if self.tcx().coroutine_is_async(*did) { debug!(?self_ty, ?obligation, "assemble_future_candidates",); candidates.vec.push(FutureCandidate); @@ -518,11 +518,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { { match movability { hir::Movability::Static => { - // Immovable generators are never `Unpin`, so + // Immovable coroutines are never `Unpin`, so // suppress the normal auto-impl candidate for it. } hir::Movability::Movable => { - // Movable generators are always `Unpin`, so add an + // Movable coroutines are always `Unpin`, so add an // unconditional builtin candidate. candidates.vec.push(BuiltinCandidate { has_nested: false }); } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index bc918d76aaa..fce439f21fa 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -84,8 +84,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } CoroutineCandidate => { - let vtable_generator = self.confirm_generator_candidate(obligation)?; - ImplSource::Builtin(BuiltinImplSource::Misc, vtable_generator) + let vtable_coroutine = self.confirm_coroutine_candidate(obligation)?; + ImplSource::Builtin(BuiltinImplSource::Misc, vtable_coroutine) } FutureCandidate => { @@ -711,23 +711,23 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { trait_obligations } - fn confirm_generator_candidate( + fn confirm_coroutine_candidate( &mut self, obligation: &PolyTraitObligation<'tcx>, ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> { - // Okay to skip binder because the args on generator types never + // Okay to skip binder because the args on coroutine types never // touch bound regions, they just capture the in-scope // type/region parameters. let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); - let ty::Coroutine(generator_def_id, args, _) = *self_ty.kind() else { + let ty::Coroutine(coroutine_def_id, args, _) = *self_ty.kind() else { bug!("closure candidate for non-closure {:?}", obligation); }; - debug!(?obligation, ?generator_def_id, ?args, "confirm_generator_candidate"); + debug!(?obligation, ?coroutine_def_id, ?args, "confirm_coroutine_candidate"); - let gen_sig = args.as_generator().poly_sig(); + let gen_sig = args.as_coroutine().poly_sig(); - // NOTE: The self-type is a generator type and hence is + // NOTE: The self-type is a coroutine type and hence is // in fact unparameterized (or at least does not reference any // regions bound in the obligation). let self_ty = obligation @@ -736,7 +736,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .no_bound_vars() .expect("unboxed closure type should not capture bound vars from the predicate"); - let trait_ref = super::util::generator_trait_ref_and_outputs( + let trait_ref = super::util::coroutine_trait_ref_and_outputs( self.tcx(), obligation.predicate.def_id(), self_ty, @@ -745,7 +745,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .map_bound(|(trait_ref, ..)| trait_ref); let nested = self.confirm_poly_trait_refs(obligation, trait_ref)?; - debug!(?trait_ref, ?nested, "generator candidate obligations"); + debug!(?trait_ref, ?nested, "coroutine candidate obligations"); Ok(nested) } @@ -754,17 +754,17 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { &mut self, obligation: &PolyTraitObligation<'tcx>, ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> { - // Okay to skip binder because the args on generator types never + // Okay to skip binder because the args on coroutine types never // touch bound regions, they just capture the in-scope // type/region parameters. let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); - let ty::Coroutine(generator_def_id, args, _) = *self_ty.kind() else { + let ty::Coroutine(coroutine_def_id, args, _) = *self_ty.kind() else { bug!("closure candidate for non-closure {:?}", obligation); }; - debug!(?obligation, ?generator_def_id, ?args, "confirm_future_candidate"); + debug!(?obligation, ?coroutine_def_id, ?args, "confirm_future_candidate"); - let gen_sig = args.as_generator().poly_sig(); + let gen_sig = args.as_coroutine().poly_sig(); let trait_ref = super::util::future_trait_ref_and_outputs( self.tcx(), @@ -1235,12 +1235,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { stack.push(args.as_closure().tupled_upvars_ty()); } ty::Coroutine(_, args, _) => { - let generator = args.as_generator(); - stack.extend([generator.tupled_upvars_ty(), generator.witness()]); + let coroutine = args.as_coroutine(); + stack.extend([coroutine.tupled_upvars_ty(), coroutine.witness()]); } ty::CoroutineWitness(def_id, args) => { let tcx = self.tcx(); - stack.extend(tcx.generator_hidden_types(def_id).map(|bty| { + stack.extend(tcx.coroutine_hidden_types(def_id).map(|bty| { let ty = bty.instantiate(tcx, args); debug_assert!(!ty.has_late_bound_regions()); ty diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 6592abd4388..67cb39bc004 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2190,20 +2190,20 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } ty::Coroutine(_, args, hir::Movability::Movable) => { - if self.tcx().features().generator_clone { + if self.tcx().features().coroutine_clone { let resolved_upvars = - self.infcx.shallow_resolve(args.as_generator().tupled_upvars_ty()); + self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty()); let resolved_witness = - self.infcx.shallow_resolve(args.as_generator().witness()); + self.infcx.shallow_resolve(args.as_coroutine().witness()); if resolved_upvars.is_ty_var() || resolved_witness.is_ty_var() { // Not yet resolved. Ambiguous } else { let all = args - .as_generator() + .as_coroutine() .upvar_tys() .iter() - .chain([args.as_generator().witness()]) + .chain([args.as_coroutine().witness()]) .collect::<Vec<_>>(); Where(obligation.predicate.rebind(all)) } @@ -2213,7 +2213,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } ty::CoroutineWitness(def_id, ref args) => { - let hidden_types = bind_generator_hidden_types_above( + let hidden_types = bind_coroutine_hidden_types_above( self.infcx, def_id, args, @@ -2312,13 +2312,13 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } ty::Coroutine(_, ref args, _) => { - let ty = self.infcx.shallow_resolve(args.as_generator().tupled_upvars_ty()); - let witness = args.as_generator().witness(); + let ty = self.infcx.shallow_resolve(args.as_coroutine().tupled_upvars_ty()); + let witness = args.as_coroutine().witness(); t.rebind([ty].into_iter().chain(iter::once(witness)).collect()) } ty::CoroutineWitness(def_id, ref args) => { - bind_generator_hidden_types_above(self.infcx, def_id, args, t.bound_vars()) + bind_coroutine_hidden_types_above(self.infcx, def_id, args, t.bound_vars()) } // For `PhantomData<T>`, we pass `T`. @@ -3054,12 +3054,12 @@ pub enum ProjectionMatchesProjection { No, } -/// Replace all regions inside the generator interior with late bound regions. +/// Replace all regions inside the coroutine interior with late bound regions. /// Note that each region slot in the types gets a new fresh late bound region, which means that /// none of the regions inside relate to any other, even if typeck had previously found constraints /// that would cause them to be related. #[instrument(level = "trace", skip(infcx), ret)] -fn bind_generator_hidden_types_above<'tcx>( +fn bind_coroutine_hidden_types_above<'tcx>( infcx: &InferCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>, @@ -3074,7 +3074,7 @@ fn bind_generator_hidden_types_above<'tcx>( let mut counter = num_bound_variables; let hidden_types: Vec<_> = tcx - .generator_hidden_types(def_id) + .coroutine_hidden_types(def_id) // Deduplicate tys to avoid repeated work. .filter(|bty| seen_tys.insert(*bty)) .map(|mut bty| { diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 4ef2027d7e8..47ed4e20edc 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -275,7 +275,7 @@ pub fn closure_trait_ref_and_return_type<'tcx>( sig.map_bound(|sig| (trait_ref, sig.output())) } -pub fn generator_trait_ref_and_outputs<'tcx>( +pub fn coroutine_trait_ref_and_outputs<'tcx>( tcx: TyCtxt<'tcx>, fn_trait_def_id: DefId, self_ty: Ty<'tcx>, diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index b78794f335a..fe5b625e483 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -673,13 +673,13 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { } ty::Coroutine(did, args, ..) => { - // Walk ALL the types in the generator: this will + // Walk ALL the types in the coroutine: this will // include the upvar types as well as the yield // type. Note that this is mildly distinct from // the closure case, where we have to be careful // about the signature of the closure. We don't // have the problem of implied bounds here since - // generators don't take arguments. + // coroutines don't take arguments. let obligations = self.nominal_obligations(did, args); self.out.extend(obligations); } diff --git a/compiler/rustc_ty_utils/messages.ftl b/compiler/rustc_ty_utils/messages.ftl index c416aa52a24..ae795ef2214 100644 --- a/compiler/rustc_ty_utils/messages.ftl +++ b/compiler/rustc_ty_utils/messages.ftl @@ -60,6 +60,6 @@ ty_utils_tuple_not_supported = tuple construction is not supported in generic co ty_utils_unexpected_fnptr_associated_item = `FnPtr` trait with unexpected associated item -ty_utils_yield_not_supported = generator control flow is not allowed in generic constants +ty_utils_yield_not_supported = coroutine control flow is not allowed in generic constants ty_utils_zero_length_simd_type = monomorphising SIMD type `{$ty}` of zero length diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index f6eec38af7b..fcf6626bbf0 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -98,7 +98,7 @@ fn fn_sig_for_fn_abi<'tcx>( ) } ty::Coroutine(did, args, _) => { - let sig = args.as_generator().poly_sig(); + let sig = args.as_coroutine().poly_sig(); let bound_vars = tcx.mk_bound_variable_kinds_from_iter( sig.bound_vars().iter().chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))), @@ -116,11 +116,11 @@ fn fn_sig_for_fn_abi<'tcx>( let env_ty = Ty::new_adt(tcx, pin_adt_ref, pin_args); let sig = sig.skip_binder(); - // The `FnSig` and the `ret_ty` here is for a generators main + // The `FnSig` and the `ret_ty` here is for a coroutines main // `Coroutine::resume(...) -> CoroutineState` function in case we - // have an ordinary generator, or the `Future::poll(...) -> Poll` - // function in case this is a special generator backing an async construct. - let (resume_ty, ret_ty) = if tcx.generator_is_async(did) { + // have an ordinary coroutine, or the `Future::poll(...) -> Poll` + // function in case this is a special coroutine backing an async construct. + let (resume_ty, ret_ty) = if tcx.coroutine_is_async(did) { // The signature should be `Future::poll(_, &mut Context<'_>) -> Poll<Output>` let poll_did = tcx.require_lang_item(LangItem::Poll, None); let poll_adt_ref = tcx.adt_def(poll_did); diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 7f3e2cefd02..0e9d79c15c3 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -246,12 +246,12 @@ fn resolve_associated_item<'tcx>( }) } } else if Some(trait_ref.def_id) == lang_items.future_trait() { - let ty::Coroutine(generator_def_id, args, _) = *rcvr_args.type_at(0).kind() else { + let ty::Coroutine(coroutine_def_id, args, _) = *rcvr_args.type_at(0).kind() else { bug!() }; if Some(trait_item_id) == tcx.lang_items().future_poll_fn() { // `Future::poll` is generated by the compiler. - Some(Instance { def: ty::InstanceDef::Item(generator_def_id), args: args }) + Some(Instance { def: ty::InstanceDef::Item(coroutine_def_id), args: args }) } else { // All other methods are default methods of the `Future` trait. // (this assumes that `ImplSource::Builtin` is only used for methods on `Future`) @@ -259,7 +259,7 @@ fn resolve_associated_item<'tcx>( Some(Instance::new(trait_item_id, rcvr_args)) } } else if Some(trait_ref.def_id) == lang_items.gen_trait() { - let ty::Coroutine(generator_def_id, args, _) = *rcvr_args.type_at(0).kind() else { + let ty::Coroutine(coroutine_def_id, args, _) = *rcvr_args.type_at(0).kind() else { bug!() }; if cfg!(debug_assertions) && tcx.item_name(trait_item_id) != sym::resume { @@ -268,12 +268,12 @@ fn resolve_associated_item<'tcx>( // `InstanceDef::Item` pointing to a trait default method body if // it is given a default implementation by the trait. span_bug!( - tcx.def_span(generator_def_id), - "no definition for `{trait_ref}::{}` for built-in generator type", + tcx.def_span(coroutine_def_id), + "no definition for `{trait_ref}::{}` for built-in coroutine type", tcx.item_name(trait_item_id) ) } - Some(Instance { def: ty::InstanceDef::Item(generator_def_id), args }) + Some(Instance { def: ty::InstanceDef::Item(coroutine_def_id), args }) } else if tcx.fn_trait_kind_from_def_id(trait_ref.def_id).is_some() { // FIXME: This doesn't check for malformed libcore that defines, e.g., // `trait Fn { fn call_once(&self) { .. } }`. This is mostly for extension diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 8cb4162563e..283862b5e1c 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -314,7 +314,7 @@ fn layout_of_uncached<'tcx>( tcx.mk_layout(unit) } - ty::Coroutine(def_id, args, _) => generator_layout(cx, ty, def_id, args)?, + ty::Coroutine(def_id, args, _) => coroutine_layout(cx, ty, def_id, args)?, ty::Closure(_, ref args) => { let tys = args.as_closure().upvar_tys(); @@ -593,7 +593,7 @@ enum SavedLocalEligibility { Ineligible(Option<FieldIdx>), } -// When laying out generators, we divide our saved local fields into two +// When laying out coroutines, we divide our saved local fields into two // categories: overlap-eligible and overlap-ineligible. // // Those fields which are ineligible for overlap go in a "prefix" at the @@ -613,7 +613,7 @@ enum SavedLocalEligibility { // of any variant. /// Compute the eligibility and assignment of each local. -fn generator_saved_local_eligibility( +fn coroutine_saved_local_eligibility( info: &CoroutineLayout<'_>, ) -> (BitSet<CoroutineSavedLocal>, IndexVec<CoroutineSavedLocal, SavedLocalEligibility>) { use SavedLocalEligibility::*; @@ -622,7 +622,7 @@ fn generator_saved_local_eligibility( IndexVec::from_elem(Unassigned, &info.field_tys); // The saved locals not eligible for overlap. These will get - // "promoted" to the prefix of our generator. + // "promoted" to the prefix of our coroutine. let mut ineligible_locals = BitSet::new_empty(info.field_tys.len()); // Figure out which of our saved locals are fields in only @@ -660,7 +660,7 @@ fn generator_saved_local_eligibility( for local_b in info.storage_conflicts.iter(local_a) { // local_a and local_b are storage live at the same time, therefore they - // cannot overlap in the generator layout. The only way to guarantee + // cannot overlap in the coroutine layout. The only way to guarantee // this is if they are in the same variant, or one is ineligible // (which means it is stored in every variant). if ineligible_locals.contains(local_b) || assignments[local_a] == assignments[local_b] { @@ -705,13 +705,13 @@ fn generator_saved_local_eligibility( assignments[local] = Ineligible(Some(FieldIdx::from_usize(idx))); } } - debug!("generator saved local assignments: {:?}", assignments); + debug!("coroutine saved local assignments: {:?}", assignments); (ineligible_locals, assignments) } -/// Compute the full generator layout. -fn generator_layout<'tcx>( +/// Compute the full coroutine layout. +fn coroutine_layout<'tcx>( cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, ty: Ty<'tcx>, def_id: hir::def_id::DefId, @@ -721,15 +721,15 @@ fn generator_layout<'tcx>( let tcx = cx.tcx; let subst_field = |ty: Ty<'tcx>| EarlyBinder::bind(ty).instantiate(tcx, args); - let Some(info) = tcx.generator_layout(def_id) else { + let Some(info) = tcx.coroutine_layout(def_id) else { return Err(error(cx, LayoutError::Unknown(ty))); }; - let (ineligible_locals, assignments) = generator_saved_local_eligibility(&info); + let (ineligible_locals, assignments) = coroutine_saved_local_eligibility(&info); // Build a prefix layout, including "promoting" all ineligible // locals as part of the prefix. We compute the layout of all of // these fields at once to get optimal packing. - let tag_index = args.as_generator().prefix_tys().len(); + let tag_index = args.as_coroutine().prefix_tys().len(); // `info.variant_fields` already accounts for the reserved variants, so no need to add them. let max_discr = (info.variant_fields.len() - 1) as u128; @@ -746,7 +746,7 @@ fn generator_layout<'tcx>( .map(|ty| Ty::new_maybe_uninit(tcx, ty)) .map(|ty| Ok(cx.layout_of(ty)?.layout)); let prefix_layouts = args - .as_generator() + .as_coroutine() .prefix_tys() .iter() .map(|ty| Ok(cx.layout_of(ty)?.layout)) @@ -907,7 +907,7 @@ fn generator_layout<'tcx>( max_repr_align: None, unadjusted_abi_align: align.abi, }); - debug!("generator layout ({:?}): {:#?}", ty, layout); + debug!("coroutine layout ({:?}): {:#?}", ty, layout); Ok(layout) } @@ -957,10 +957,10 @@ fn record_layout_for_printing_outlined<'tcx>( } ty::Coroutine(def_id, args, _) => { - debug!("print-type-size t: `{:?}` record generator", layout.ty); + debug!("print-type-size t: `{:?}` record coroutine", layout.ty); // Coroutines always have a begin/poisoned/end state with additional suspend points let (variant_infos, opt_discr_size) = - variant_info_for_generator(cx, layout, def_id, args); + variant_info_for_coroutine(cx, layout, def_id, args); record(DataTypeKind::Coroutine, false, opt_discr_size, variant_infos); } @@ -1046,7 +1046,7 @@ fn variant_info_for_adt<'tcx>( } } -fn variant_info_for_generator<'tcx>( +fn variant_info_for_coroutine<'tcx>( cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, layout: TyAndLayout<'tcx>, def_id: DefId, @@ -1056,12 +1056,12 @@ fn variant_info_for_generator<'tcx>( return (vec![], None); }; - let generator = cx.tcx.optimized_mir(def_id).generator_layout().unwrap(); + let coroutine = cx.tcx.optimized_mir(def_id).coroutine_layout().unwrap(); let upvar_names = cx.tcx.closure_saved_names_of_captured_variables(def_id); let mut upvars_size = Size::ZERO; let upvar_fields: Vec<_> = args - .as_generator() + .as_coroutine() .upvar_tys() .iter() .zip(upvar_names) @@ -1080,7 +1080,7 @@ fn variant_info_for_generator<'tcx>( }) .collect(); - let mut variant_infos: Vec<_> = generator + let mut variant_infos: Vec<_> = coroutine .variant_fields .iter_enumerated() .map(|(variant_idx, variant_def)| { @@ -1096,8 +1096,8 @@ fn variant_info_for_generator<'tcx>( variant_size = variant_size.max(offset + field_layout.size); FieldInfo { kind: FieldKind::CoroutineLocal, - name: generator.field_names[*local].unwrap_or(Symbol::intern(&format!( - ".generator_field{}", + name: coroutine.field_names[*local].unwrap_or(Symbol::intern(&format!( + ".coroutine_field{}", local.as_usize() ))), offset: offset.bytes(), @@ -1115,8 +1115,8 @@ fn variant_info_for_generator<'tcx>( // This `if` deserves some explanation. // - // The layout code has a choice of where to place the discriminant of this generator. - // If the discriminant of the generator is placed early in the layout (before the + // The layout code has a choice of where to place the discriminant of this coroutine. + // If the discriminant of the coroutine is placed early in the layout (before the // variant's own fields), then it'll implicitly be counted towards the size of the // variant, since we use the maximum offset to calculate size. // (side-note: I know this is a bit problematic given upvars placement, etc). @@ -1147,7 +1147,7 @@ fn variant_info_for_generator<'tcx>( // The first three variants are hardcoded to be `UNRESUMED`, `RETURNED` and `POISONED`. // We will move the `RETURNED` and `POISONED` elements to the end so we - // are left with a sorting order according to the generators yield points: + // are left with a sorting order according to the coroutines yield points: // First `Unresumed`, then the `SuspendN` followed by `Returned` and `Panicked` (POISONED). let end_states = variant_infos.drain(1..=2); let end_states: Vec<_> = end_states.collect(); diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index c2190118b2e..08127304741 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -130,9 +130,9 @@ where for component in components { match *component.kind() { - // The information required to determine whether a generator has drop is + // The information required to determine whether a coroutine has drop is // computed on MIR, while this very method is used to build MIR. - // To avoid cycles, we consider that generators always require drop. + // To avoid cycles, we consider that coroutines always require drop. ty::Coroutine(..) => { return Some(Err(AlwaysRequiresDrop)); } diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index a297f9af56a..0010570e7b3 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -322,7 +322,7 @@ fn opaque_types_defined_by<'tcx>(tcx: TyCtxt<'tcx>, item: LocalDefId) -> &'tcx [ | DefKind::LifetimeParam | DefKind::GlobalAsm | DefKind::Impl { .. } => {} - // Closures and generators are type checked with their parent, so there is no difference here. + // Closures and coroutines are type checked with their parent, so there is no difference here. DefKind::Closure | DefKind::Coroutine | DefKind::InlineConst => { return tcx.opaque_types_defined_by(tcx.local_parent(item)); } diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 954972bad26..91bfce9a142 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -15,8 +15,8 @@ use crate::{DebruijnIndex, DebugWithInfcx, InferCtxtLike, OptWithInfcx}; use self::TyKind::*; -/// The movability of a generator / closure literal: -/// whether a generator contains self-references, causing it to be `!Unpin`. +/// The movability of a coroutine / closure literal: +/// whether a coroutine contains self-references, causing it to be `!Unpin`. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)] #[derive(HashStable_Generic)] pub enum Movability { @@ -195,30 +195,30 @@ pub enum TyKind<I: Interner> { /// `ClosureArgs` for more details. Closure(I::DefId, I::GenericArgs), - /// The anonymous type of a generator. Used to represent the type of + /// The anonymous type of a coroutine. Used to represent the type of /// `|a| yield a`. /// - /// For more info about generator args, visit the documentation for + /// For more info about coroutine args, visit the documentation for /// `CoroutineArgs`. Coroutine(I::DefId, I::GenericArgs, Movability), - /// A type representing the types stored inside a generator. + /// A type representing the types stored inside a coroutine. /// This should only appear as part of the `CoroutineArgs`. /// /// Unlike upvars, the witness can reference lifetimes from - /// inside of the generator itself. To deal with them in - /// the type of the generator, we convert them to higher ranked + /// inside of the coroutine itself. To deal with them in + /// the type of the coroutine, we convert them to higher ranked /// lifetimes bound by the witness itself. /// /// This variant is only using when `drop_tracking_mir` is set. - /// This contains the `DefId` and the `GenericArgsRef` of the generator. - /// The actual witness types are computed on MIR by the `mir_generator_witnesses` query. + /// This contains the `DefId` and the `GenericArgsRef` of the coroutine. + /// The actual witness types are computed on MIR by the `mir_coroutine_witnesses` query. /// - /// Looking at the following example, the witness for this generator + /// Looking at the following example, the witness for this coroutine /// may end up as something like `for<'a> [Vec<i32>, &'a Vec<i32>]`: /// /// ```ignore UNSOLVED (ask @compiler-errors, should this error? can we just swap the yields?) - /// #![feature(generators)] + /// #![feature(coroutines)] /// |a| { /// let x = &vec![3]; /// yield a; diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs index 4de1f8940d9..9e73dd968ff 100644 --- a/compiler/stable_mir/src/mir/body.rs +++ b/compiler/stable_mir/src/mir/body.rs @@ -228,7 +228,7 @@ pub enum Rvalue { /// has a destructor. /// /// Disallowed after deaggregation for all aggregate kinds except `Array` and `Coroutine`. After - /// generator lowering, `Coroutine` aggregate kinds are disallowed too. + /// coroutine lowering, `Coroutine` aggregate kinds are disallowed too. Aggregate(AggregateKind, Vec<Operand>), /// * `Offset` has the same semantics as `<*const T>::offset`, except that the second |
