Skip to content

Commit aa7f5f1

Browse files
committed
Auto merge of #141762 - compiler-errors:witnesser, r=<try>
[experimental] Make witnesses more eager r? lcnr
2 parents 6de3a73 + 7bff9fb commit aa7f5f1

File tree

18 files changed

+187
-180
lines changed

18 files changed

+187
-180
lines changed

compiler/rustc_hir_typeck/src/closure.rs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -163,16 +163,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
163163
// Resume type defaults to `()` if the coroutine has no argument.
164164
let resume_ty = liberated_sig.inputs().get(0).copied().unwrap_or(tcx.types.unit);
165165

166-
// In the new solver, we can just instantiate this eagerly
167-
// with the witness. This will ensure that goals that don't need
168-
// to stall on interior types will get processed eagerly.
169-
let interior = if self.next_trait_solver() {
170-
Ty::new_coroutine_witness(tcx, expr_def_id.to_def_id(), parent_args)
171-
} else {
172-
self.next_ty_var(expr_span)
173-
};
174-
175-
self.deferred_coroutine_interiors.borrow_mut().push((expr_def_id, interior));
166+
let interior = Ty::new_coroutine_witness(tcx, expr_def_id.to_def_id(), parent_args);
176167

177168
// Coroutines that come from coroutine closures have not yet determined
178169
// their kind ty, so make a fresh infer var which will be constrained

compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs

Lines changed: 12 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -628,50 +628,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
628628
// trigger query cycle ICEs, as doing so requires MIR.
629629
self.select_obligations_where_possible(|_| {});
630630

631-
let coroutines = std::mem::take(&mut *self.deferred_coroutine_interiors.borrow_mut());
632-
debug!(?coroutines);
633-
634-
let mut obligations = vec![];
635-
636-
if !self.next_trait_solver() {
637-
for &(coroutine_def_id, interior) in coroutines.iter() {
638-
debug!(?coroutine_def_id);
639-
640-
// Create the `CoroutineWitness` type that we will unify with `interior`.
641-
let args = ty::GenericArgs::identity_for_item(
642-
self.tcx,
643-
self.tcx.typeck_root_def_id(coroutine_def_id.to_def_id()),
644-
);
645-
let witness =
646-
Ty::new_coroutine_witness(self.tcx, coroutine_def_id.to_def_id(), args);
647-
648-
// Unify `interior` with `witness` and collect all the resulting obligations.
649-
let span = self.tcx.hir_body_owned_by(coroutine_def_id).value.span;
650-
let ty::Infer(ty::InferTy::TyVar(_)) = interior.kind() else {
651-
span_bug!(span, "coroutine interior witness not infer: {:?}", interior.kind())
652-
};
653-
let ok = self
654-
.at(&self.misc(span), self.param_env)
655-
// Will never define opaque types, as all we do is instantiate a type variable.
656-
.eq(DefineOpaqueTypes::Yes, interior, witness)
657-
.expect("Failed to unify coroutine interior type");
658-
659-
obligations.extend(ok.obligations);
660-
}
661-
}
631+
let ty::TypingMode::Analysis { defining_opaque_types_and_generators } = self.typing_mode()
632+
else {
633+
bug!();
634+
};
662635

663-
if !coroutines.is_empty() {
664-
obligations.extend(
636+
if defining_opaque_types_and_generators
637+
.iter()
638+
.any(|def_id| self.tcx.is_coroutine(def_id.to_def_id()))
639+
{
640+
self.typeck_results.borrow_mut().coroutine_stalled_predicates.extend(
665641
self.fulfillment_cx
666642
.borrow_mut()
667-
.drain_stalled_obligations_for_coroutines(&self.infcx),
643+
.drain_stalled_obligations_for_coroutines(&self.infcx)
644+
.into_iter()
645+
.map(|o| (o.predicate, o.cause)),
668646
);
669647
}
670-
671-
self.typeck_results
672-
.borrow_mut()
673-
.coroutine_stalled_predicates
674-
.extend(obligations.into_iter().map(|o| (o.predicate, o.cause)));
675648
}
676649

677650
#[instrument(skip(self), level = "debug")]

compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,6 @@ pub(crate) struct TypeckRootCtxt<'tcx> {
6363

6464
pub(super) deferred_asm_checks: RefCell<Vec<(&'tcx hir::InlineAsm<'tcx>, HirId)>>,
6565

66-
pub(super) deferred_coroutine_interiors: RefCell<Vec<(LocalDefId, Ty<'tcx>)>>,
67-
6866
pub(super) deferred_repeat_expr_checks:
6967
RefCell<Vec<(&'tcx hir::Expr<'tcx>, Ty<'tcx>, ty::Const<'tcx>)>>,
7068

@@ -103,7 +101,6 @@ impl<'tcx> TypeckRootCtxt<'tcx> {
103101
deferred_cast_checks: RefCell::new(Vec::new()),
104102
deferred_transmute_checks: RefCell::new(Vec::new()),
105103
deferred_asm_checks: RefCell::new(Vec::new()),
106-
deferred_coroutine_interiors: RefCell::new(Vec::new()),
107104
deferred_repeat_expr_checks: RefCell::new(Vec::new()),
108105
diverging_type_vars: RefCell::new(Default::default()),
109106
infer_var_info: RefCell::new(Default::default()),

compiler/rustc_middle/src/ty/context.rs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -698,17 +698,13 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
698698
self,
699699
defining_anchor: Self::LocalDefId,
700700
) -> Self::LocalDefIds {
701-
if self.next_trait_solver_globally() {
702-
let coroutines_defined_by = self
703-
.nested_bodies_within(defining_anchor)
704-
.iter()
705-
.filter(|def_id| self.is_coroutine(def_id.to_def_id()));
706-
self.mk_local_def_ids_from_iter(
707-
self.opaque_types_defined_by(defining_anchor).iter().chain(coroutines_defined_by),
708-
)
709-
} else {
710-
self.opaque_types_defined_by(defining_anchor)
711-
}
701+
let coroutines_defined_by = self
702+
.nested_bodies_within(defining_anchor)
703+
.iter()
704+
.filter(|def_id| self.is_coroutine(def_id.to_def_id()));
705+
self.mk_local_def_ids_from_iter(
706+
self.opaque_types_defined_by(defining_anchor).iter().chain(coroutines_defined_by),
707+
)
712708
}
713709
}
714710

compiler/rustc_trait_selection/src/infer.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ impl<'tcx> InferCtxt<'tcx> {
3333
let ty = self.resolve_vars_if_possible(ty);
3434

3535
// FIXME(#132279): This should be removed as it causes us to incorrectly
36-
// handle opaques in their defining scope.
37-
if !self.next_trait_solver() && !(param_env, ty).has_infer() {
36+
// handle opaques in their defining scope, and stalled coroutines.
37+
if !self.next_trait_solver() && !(param_env, ty).has_infer() && !ty.has_coroutines() {
3838
return self.tcx.type_is_copy_modulo_regions(self.typing_env(param_env), ty);
3939
}
4040

compiler/rustc_trait_selection/src/solve.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ mod normalize;
77
mod select;
88

99
pub(crate) use delegate::SolverDelegate;
10-
pub use fulfill::{FulfillmentCtxt, NextSolverError};
10+
pub use fulfill::{FulfillmentCtxt, NextSolverError, StalledOnCoroutines};
1111
pub(crate) use normalize::deeply_normalize_for_diagnostics;
1212
pub use normalize::{
1313
deeply_normalize, deeply_normalize_with_skipped_universes,

compiler/rustc_trait_selection/src/solve/fulfill.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ where
259259
&mut self,
260260
infcx: &InferCtxt<'tcx>,
261261
) -> PredicateObligations<'tcx> {
262-
let stalled_generators = match infcx.typing_mode() {
262+
let stalled_coroutines = match infcx.typing_mode() {
263263
TypingMode::Analysis { defining_opaque_types_and_generators } => {
264264
defining_opaque_types_and_generators
265265
}
@@ -269,7 +269,7 @@ where
269269
| TypingMode::PostAnalysis => return Default::default(),
270270
};
271271

272-
if stalled_generators.is_empty() {
272+
if stalled_coroutines.is_empty() {
273273
return Default::default();
274274
}
275275

@@ -280,7 +280,7 @@ where
280280
.visit_proof_tree(
281281
obl.as_goal(),
282282
&mut StalledOnCoroutines {
283-
stalled_generators,
283+
stalled_coroutines,
284284
span: obl.cause.span,
285285
cache: Default::default(),
286286
},
@@ -302,10 +302,10 @@ where
302302
///
303303
/// This function can be also return false positives, which will lead to poor diagnostics
304304
/// so we want to keep this visitor *precise* too.
305-
struct StalledOnCoroutines<'tcx> {
306-
stalled_generators: &'tcx ty::List<LocalDefId>,
307-
span: Span,
308-
cache: DelayedSet<Ty<'tcx>>,
305+
pub struct StalledOnCoroutines<'tcx> {
306+
pub stalled_coroutines: &'tcx ty::List<LocalDefId>,
307+
pub span: Span,
308+
pub cache: DelayedSet<Ty<'tcx>>,
309309
}
310310

311311
impl<'tcx> inspect::ProofTreeVisitor<'tcx> for StalledOnCoroutines<'tcx> {
@@ -335,7 +335,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for StalledOnCoroutines<'tcx> {
335335
}
336336

337337
if let ty::CoroutineWitness(def_id, _) = *ty.kind()
338-
&& def_id.as_local().is_some_and(|def_id| self.stalled_generators.contains(&def_id))
338+
&& def_id.as_local().is_some_and(|def_id| self.stalled_coroutines.contains(&def_id))
339339
{
340340
return ControlFlow::Break(());
341341
}

compiler/rustc_trait_selection/src/traits/fulfill.rs

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::marker::PhantomData;
33
use rustc_data_structures::obligation_forest::{
44
Error, ForestObligation, ObligationForest, ObligationProcessor, Outcome, ProcessResult,
55
};
6+
use rustc_hir::def_id::LocalDefId;
67
use rustc_infer::infer::DefineOpaqueTypes;
78
use rustc_infer::traits::{
89
FromSolverError, PolyTraitObligation, PredicateObligations, ProjectionCacheKey, SelectionError,
@@ -11,7 +12,10 @@ use rustc_infer::traits::{
1112
use rustc_middle::bug;
1213
use rustc_middle::ty::abstract_const::NotConstEvaluatable;
1314
use rustc_middle::ty::error::{ExpectedFound, TypeError};
14-
use rustc_middle::ty::{self, Binder, Const, GenericArgsRef, TypeVisitableExt, TypingMode};
15+
use rustc_middle::ty::{
16+
self, Binder, Const, GenericArgsRef, TypeVisitable, TypeVisitableExt, TypingMode,
17+
};
18+
use rustc_span::DUMMY_SP;
1519
use thin_vec::ThinVec;
1620
use tracing::{debug, debug_span, instrument};
1721

@@ -24,6 +28,7 @@ use super::{
2428
};
2529
use crate::error_reporting::InferCtxtErrorExt;
2630
use crate::infer::{InferCtxt, TyOrConstInferVar};
31+
use crate::solve::StalledOnCoroutines;
2732
use crate::traits::normalize::normalize_with_depth_to;
2833
use crate::traits::project::{PolyProjectionObligation, ProjectionCacheKeyExt as _};
2934
use crate::traits::query::evaluate_obligation::InferCtxtExt;
@@ -166,15 +171,33 @@ where
166171
&mut self,
167172
infcx: &InferCtxt<'tcx>,
168173
) -> PredicateObligations<'tcx> {
169-
let mut processor =
170-
DrainProcessor { removed_predicates: PredicateObligations::new(), infcx };
174+
let stalled_coroutines = match infcx.typing_mode() {
175+
TypingMode::Analysis { defining_opaque_types_and_generators } => {
176+
defining_opaque_types_and_generators
177+
}
178+
TypingMode::Coherence
179+
| TypingMode::Borrowck { defining_opaque_types: _ }
180+
| TypingMode::PostBorrowckAnalysis { defined_opaque_types: _ }
181+
| TypingMode::PostAnalysis => return Default::default(),
182+
};
183+
184+
if stalled_coroutines.is_empty() {
185+
return Default::default();
186+
}
187+
188+
let mut processor = DrainProcessor {
189+
infcx,
190+
removed_predicates: PredicateObligations::new(),
191+
stalled_coroutines,
192+
};
171193
let outcome: Outcome<_, _> = self.predicates.process_obligations(&mut processor);
172194
assert!(outcome.errors.is_empty());
173195
return processor.removed_predicates;
174196

175197
struct DrainProcessor<'a, 'tcx> {
176198
infcx: &'a InferCtxt<'tcx>,
177199
removed_predicates: PredicateObligations<'tcx>,
200+
stalled_coroutines: &'tcx ty::List<LocalDefId>,
178201
}
179202

180203
impl<'tcx> ObligationProcessor for DrainProcessor<'_, 'tcx> {
@@ -183,10 +206,14 @@ where
183206
type OUT = Outcome<Self::Obligation, Self::Error>;
184207

185208
fn needs_process_obligation(&self, pending_obligation: &Self::Obligation) -> bool {
186-
pending_obligation
187-
.stalled_on
188-
.iter()
189-
.any(|&var| self.infcx.ty_or_const_infer_var_changed(var))
209+
self.infcx
210+
.resolve_vars_if_possible(pending_obligation.obligation.predicate)
211+
.visit_with(&mut StalledOnCoroutines {
212+
stalled_coroutines: self.stalled_coroutines,
213+
span: DUMMY_SP,
214+
cache: Default::default(),
215+
})
216+
.is_break()
190217
}
191218

192219
fn process_obligation(

compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -804,6 +804,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
804804
}
805805
}
806806

807+
ty::CoroutineWitness(def_id, _) => {
808+
if self.should_stall_coroutine_witness(def_id) {
809+
candidates.ambiguous = true;
810+
} else {
811+
candidates.vec.push(AutoImplCandidate);
812+
}
813+
}
814+
807815
ty::Bool
808816
| ty::Char
809817
| ty::Int(_)
@@ -823,7 +831,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
823831
| ty::Coroutine(..)
824832
| ty::Never
825833
| ty::Tuple(_)
826-
| ty::CoroutineWitness(..)
827834
| ty::UnsafeBinder(_) => {
828835
// Only consider auto impls of unsafe traits when there are
829836
// no unsafe fields.

compiler/rustc_trait_selection/src/traits/select/mod.rs

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1508,7 +1508,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
15081508
defining_opaque_types_and_generators: defining_opaque_types,
15091509
}
15101510
| TypingMode::Borrowck { defining_opaque_types } => {
1511-
defining_opaque_types.is_empty() || !pred.has_opaque_types()
1511+
defining_opaque_types.is_empty()
1512+
|| (!pred.has_opaque_types() && !pred.has_coroutines())
15121513
}
15131514
// The hidden types of `defined_opaque_types` is not local to the current
15141515
// inference context, so we can freely move this to the global cache.
@@ -2224,13 +2225,17 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
22242225
}
22252226

22262227
ty::CoroutineWitness(def_id, args) => {
2227-
let hidden_types = rebind_coroutine_witness_types(
2228-
self.infcx.tcx,
2229-
def_id,
2230-
args,
2231-
obligation.predicate.bound_vars(),
2232-
);
2233-
Where(hidden_types)
2228+
if self.should_stall_coroutine_witness(def_id) {
2229+
Ambiguous
2230+
} else {
2231+
let hidden_types = rebind_coroutine_witness_types(
2232+
self.infcx.tcx,
2233+
def_id,
2234+
args,
2235+
obligation.predicate.bound_vars(),
2236+
);
2237+
Where(hidden_types)
2238+
}
22342239
}
22352240

22362241
ty::Closure(_, args) => {
@@ -2856,6 +2861,22 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
28562861

28572862
obligations
28582863
}
2864+
2865+
fn should_stall_coroutine_witness(&self, def_id: DefId) -> bool {
2866+
match self.infcx.typing_mode() {
2867+
TypingMode::Analysis { defining_opaque_types_and_generators: stalled_generators } => {
2868+
if def_id.as_local().is_some_and(|def_id| stalled_generators.contains(&def_id)) {
2869+
return true;
2870+
}
2871+
}
2872+
TypingMode::Coherence
2873+
| TypingMode::PostAnalysis
2874+
| TypingMode::Borrowck { defining_opaque_types: _ }
2875+
| TypingMode::PostBorrowckAnalysis { defined_opaque_types: _ } => {}
2876+
}
2877+
2878+
false
2879+
}
28592880
}
28602881

28612882
fn rebind_coroutine_witness_types<'tcx>(

compiler/rustc_type_ir/src/flags.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@ bitflags::bitflags! {
130130

131131
/// Does this have any binders with bound vars (e.g. that need to be anonymized)?
132132
const HAS_BINDER_VARS = 1 << 23;
133+
134+
const HAS_TY_CORO = 1 << 24;
133135
}
134136
}
135137

@@ -240,10 +242,12 @@ impl<I: Interner> FlagComputation<I> {
240242
self.add_flags(TypeFlags::HAS_TY_PARAM);
241243
}
242244

243-
ty::Closure(_, args)
244-
| ty::Coroutine(_, args)
245-
| ty::CoroutineClosure(_, args)
246-
| ty::CoroutineWitness(_, args) => {
245+
ty::Closure(_, args) | ty::Coroutine(_, args) | ty::CoroutineClosure(_, args) => {
246+
self.add_args(args.as_slice());
247+
}
248+
249+
ty::CoroutineWitness(_, args) => {
250+
self.add_flags(TypeFlags::HAS_TY_CORO);
247251
self.add_args(args.as_slice());
248252
}
249253

compiler/rustc_type_ir/src/visit.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,10 @@ pub trait TypeVisitableExt<I: Interner>: TypeVisitable<I> {
269269
self.has_type_flags(TypeFlags::HAS_TY_OPAQUE)
270270
}
271271

272+
fn has_coroutines(&self) -> bool {
273+
self.has_type_flags(TypeFlags::HAS_TY_CORO)
274+
}
275+
272276
fn references_error(&self) -> bool {
273277
self.has_type_flags(TypeFlags::HAS_ERROR)
274278
}

0 commit comments

Comments
 (0)