Skip to content

Commit c5243c3

Browse files
Auto merge of #141762 - compiler-errors:witnesser, r=<try>
[experimental] Make witnesses more eager r? lcnr
2 parents 00b5262 + ec8dc45 commit c5243c3

File tree

19 files changed

+202
-184
lines changed

19 files changed

+202
-184
lines changed

compiler/rustc_hir_typeck/src/closure.rs

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

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

175166
// Coroutines that come from coroutine closures have not yet determined
176167
// 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_infer/src/infer/mod.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use rustc_data_structures::undo_log::{Rollback, UndoLogs};
2020
use rustc_data_structures::unify as ut;
2121
use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
2222
use rustc_hir as hir;
23+
use rustc_hir::def::DefKind;
2324
use rustc_hir::def_id::{DefId, LocalDefId};
2425
use rustc_macros::extension;
2526
pub use rustc_macros::{TypeFoldable, TypeVisitable};
@@ -1249,8 +1250,16 @@ impl<'tcx> InferCtxt<'tcx> {
12491250
// to handle them without proper canonicalization. This means we may cause cycle
12501251
// errors and fail to reveal opaques while inside of bodies. We should rename this
12511252
// function and require explicit comments on all use-sites in the future.
1252-
ty::TypingMode::Analysis { defining_opaque_types_and_generators: _ }
1253-
| ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
1253+
ty::TypingMode::Analysis { defining_opaque_types_and_generators } => {
1254+
TypingMode::Analysis {
1255+
defining_opaque_types_and_generators: self.tcx.mk_local_def_ids_from_iter(
1256+
defining_opaque_types_and_generators.iter().filter(|def_id| {
1257+
!matches!(self.tcx.def_kind(*def_id), DefKind::OpaqueTy)
1258+
}),
1259+
),
1260+
}
1261+
}
1262+
ty::TypingMode::Borrowck { defining_opaque_types: _ } => {
12541263
TypingMode::non_body_analysis()
12551264
}
12561265
mode @ (ty::TypingMode::Coherence

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: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ use rustc_infer::traits::{
1010
FromSolverError, PredicateObligation, PredicateObligations, TraitEngine,
1111
};
1212
use rustc_middle::ty::{
13-
self, DelayedSet, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, TypingMode,
13+
self, DelayedSet, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
14+
TypingMode,
1415
};
1516
use rustc_next_trait_solver::delegate::SolverDelegate as _;
1617
use rustc_next_trait_solver::solve::{
@@ -264,7 +265,7 @@ where
264265
&mut self,
265266
infcx: &InferCtxt<'tcx>,
266267
) -> PredicateObligations<'tcx> {
267-
let stalled_generators = match infcx.typing_mode() {
268+
let stalled_coroutines = match infcx.typing_mode() {
268269
TypingMode::Analysis { defining_opaque_types_and_generators } => {
269270
defining_opaque_types_and_generators
270271
}
@@ -274,7 +275,7 @@ where
274275
| TypingMode::PostAnalysis => return Default::default(),
275276
};
276277

277-
if stalled_generators.is_empty() {
278+
if stalled_coroutines.is_empty() {
278279
return Default::default();
279280
}
280281

@@ -285,7 +286,7 @@ where
285286
.visit_proof_tree(
286287
obl.as_goal(),
287288
&mut StalledOnCoroutines {
288-
stalled_generators,
289+
stalled_coroutines,
289290
span: obl.cause.span,
290291
cache: Default::default(),
291292
},
@@ -307,10 +308,10 @@ where
307308
///
308309
/// This function can be also return false positives, which will lead to poor diagnostics
309310
/// so we want to keep this visitor *precise* too.
310-
struct StalledOnCoroutines<'tcx> {
311-
stalled_generators: &'tcx ty::List<LocalDefId>,
312-
span: Span,
313-
cache: DelayedSet<Ty<'tcx>>,
311+
pub struct StalledOnCoroutines<'tcx> {
312+
pub stalled_coroutines: &'tcx ty::List<LocalDefId>,
313+
pub span: Span,
314+
pub cache: DelayedSet<Ty<'tcx>>,
314315
}
315316

316317
impl<'tcx> inspect::ProofTreeVisitor<'tcx> for StalledOnCoroutines<'tcx> {
@@ -340,12 +341,14 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for StalledOnCoroutines<'tcx> {
340341
}
341342

342343
if let ty::CoroutineWitness(def_id, _) = *ty.kind()
343-
&& def_id.as_local().is_some_and(|def_id| self.stalled_generators.contains(&def_id))
344+
&& def_id.as_local().is_some_and(|def_id| self.stalled_coroutines.contains(&def_id))
344345
{
345346
return ControlFlow::Break(());
347+
} else if ty.has_coroutines() {
348+
ty.super_visit_with(self)
349+
} else {
350+
ControlFlow::Continue(())
346351
}
347-
348-
ty.super_visit_with(self)
349352
}
350353
}
351354

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
@@ -820,6 +820,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
820820
}
821821
}
822822

823+
ty::CoroutineWitness(def_id, _) => {
824+
if self.should_stall_coroutine_witness(def_id) {
825+
candidates.ambiguous = true;
826+
} else {
827+
candidates.vec.push(AutoImplCandidate);
828+
}
829+
}
830+
823831
ty::Bool
824832
| ty::Char
825833
| ty::Int(_)
@@ -839,7 +847,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
839847
| ty::Coroutine(..)
840848
| ty::Never
841849
| ty::Tuple(_)
842-
| ty::CoroutineWitness(..)
843850
| ty::UnsafeBinder(_) => {
844851
// Only consider auto impls of unsafe traits when there are
845852
// no unsafe fields.

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

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2224,13 +2224,17 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
22242224
}
22252225

22262226
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)
2227+
if self.should_stall_coroutine_witness(def_id) {
2228+
Ambiguous
2229+
} else {
2230+
let hidden_types = rebind_coroutine_witness_types(
2231+
self.infcx.tcx,
2232+
def_id,
2233+
args,
2234+
obligation.predicate.bound_vars(),
2235+
);
2236+
Where(hidden_types)
2237+
}
22342238
}
22352239

22362240
ty::Closure(_, args) => {
@@ -2856,6 +2860,22 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
28562860

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

28612881
fn rebind_coroutine_witness_types<'tcx>(

0 commit comments

Comments
 (0)