From ea10870ba1b67b4175c4cd4d401ea58f4b5e9ca5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Orell=20Valerian=20Liehr?= Date: Sun, 18 May 2025 19:10:01 +0200 Subject: [PATCH] rustdoc: Rewrite auto trait impl synthesis --- .../src/traits/auto_trait.rs | 822 ------------------ .../rustc_trait_selection/src/traits/mod.rs | 2 - src/librustdoc/clean/auto_trait.rs | 494 +++++++++-- 3 files changed, 445 insertions(+), 873 deletions(-) delete mode 100644 compiler/rustc_trait_selection/src/traits/auto_trait.rs diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs deleted file mode 100644 index 09709291a4b95..0000000000000 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ /dev/null @@ -1,822 +0,0 @@ -//! Support code for rustdoc and external tools. -//! You really don't want to be using this unless you need to. - -use std::collections::VecDeque; -use std::iter; - -use rustc_data_structures::fx::{FxIndexMap, FxIndexSet, IndexEntry}; -use rustc_data_structures::unord::UnordSet; -use rustc_hir::def_id::CRATE_DEF_ID; -use rustc_infer::infer::DefineOpaqueTypes; -use rustc_middle::ty::{Region, RegionVid}; -use tracing::debug; - -use super::*; -use crate::errors::UnableToConstructConstantValue; -use crate::infer::region_constraints::{ConstraintKind, RegionConstraintData}; -use crate::regions::OutlivesEnvironmentBuildExt; -use crate::traits::project::ProjectAndUnifyResult; - -// FIXME(twk): this is obviously not nice to duplicate like that -#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)] -pub enum RegionTarget<'tcx> { - Region(Region<'tcx>), - RegionVid(RegionVid), -} - -#[derive(Default, Debug, Clone)] -pub struct RegionDeps<'tcx> { - pub larger: FxIndexSet>, - pub smaller: FxIndexSet>, -} - -pub enum AutoTraitResult { - ExplicitImpl, - PositiveImpl(A), - NegativeImpl, -} - -pub struct AutoTraitInfo<'cx> { - pub full_user_env: ty::ParamEnv<'cx>, - pub region_data: RegionConstraintData<'cx>, - pub vid_to_region: FxIndexMap>, -} - -pub struct AutoTraitFinder<'tcx> { - tcx: TyCtxt<'tcx>, -} - -impl<'tcx> AutoTraitFinder<'tcx> { - pub fn new(tcx: TyCtxt<'tcx>) -> Self { - AutoTraitFinder { tcx } - } - - /// Makes a best effort to determine whether and under which conditions an auto trait is - /// implemented for a type. For example, if you have - /// - /// ``` - /// struct Foo { data: Box } - /// ``` - /// - /// then this might return that `Foo: Send` if `T: Send` (encoded in the AutoTraitResult - /// type). The analysis attempts to account for custom impls as well as other complex cases. - /// This result is intended for use by rustdoc and other such consumers. - /// - /// (Note that due to the coinductive nature of Send, the full and correct result is actually - /// quite simple to generate. That is, when a type has no custom impl, it is Send iff its field - /// types are all Send. So, in our example, we might have that `Foo: Send` if `Box: Send`. - /// But this is often not the best way to present to the user.) - /// - /// Warning: The API should be considered highly unstable, and it may be refactored or removed - /// in the future. - pub fn find_auto_trait_generics( - &self, - ty: Ty<'tcx>, - typing_env: ty::TypingEnv<'tcx>, - trait_did: DefId, - mut auto_trait_callback: impl FnMut(AutoTraitInfo<'tcx>) -> A, - ) -> AutoTraitResult { - let tcx = self.tcx; - - let trait_ref = ty::TraitRef::new(tcx, trait_did, [ty]); - - let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env); - let mut selcx = SelectionContext::new(&infcx); - for polarity in [ty::PredicatePolarity::Positive, ty::PredicatePolarity::Negative] { - let result = selcx.select(&Obligation::new( - tcx, - ObligationCause::dummy(), - orig_env, - ty::TraitPredicate { trait_ref, polarity }, - )); - if let Ok(Some(ImplSource::UserDefined(_))) = result { - debug!("find_auto_trait_generics({trait_ref:?}): manual impl found, bailing out"); - // If an explicit impl exists, it always takes priority over an auto impl - return AutoTraitResult::ExplicitImpl; - } - } - - let (infcx, orig_env) = tcx.infer_ctxt().build_with_typing_env(typing_env); - let mut fresh_preds = FxIndexSet::default(); - - // Due to the way projections are handled by SelectionContext, we need to run - // evaluate_predicates twice: once on the original param env, and once on the result of - // the first evaluate_predicates call. - // - // The problem is this: most of rustc, including SelectionContext and traits::project, - // are designed to work with a concrete usage of a type (e.g., Vec - // fn() { Vec }. This information will generally never change - given - // the 'T' in fn() { ... }, we'll never know anything else about 'T'. - // If we're unable to prove that 'T' implements a particular trait, we're done - - // there's nothing left to do but error out. - // - // However, synthesizing an auto trait impl works differently. Here, we start out with - // a set of initial conditions - the ParamEnv of the struct/enum/union we're dealing - // with - and progressively discover the conditions we need to fulfill for it to - // implement a certain auto trait. This ends up breaking two assumptions made by trait - // selection and projection: - // - // * We can always cache the result of a particular trait selection for the lifetime of - // an InfCtxt - // * Given a projection bound such as '::SomeItem = K', if 'T: - // SomeTrait' doesn't hold, then we don't need to care about the 'SomeItem = K' - // - // We fix the first assumption by manually clearing out all of the InferCtxt's caches - // in between calls to SelectionContext.select. This allows us to keep all of the - // intermediate types we create bound to the 'tcx lifetime, rather than needing to lift - // them between calls. - // - // We fix the second assumption by reprocessing the result of our first call to - // evaluate_predicates. Using the example of '::SomeItem = K', our first - // pass will pick up 'T: SomeTrait', but not 'SomeItem = K'. On our second pass, - // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing - // SelectionContext to return it back to us. - - let Some((new_env, user_env)) = - self.evaluate_predicates(&infcx, trait_did, ty, orig_env, orig_env, &mut fresh_preds) - else { - return AutoTraitResult::NegativeImpl; - }; - - let (full_env, full_user_env) = self - .evaluate_predicates(&infcx, trait_did, ty, new_env, user_env, &mut fresh_preds) - .unwrap_or_else(|| { - panic!("Failed to fully process: {ty:?} {trait_did:?} {orig_env:?}") - }); - - debug!( - "find_auto_trait_generics({:?}): fulfilling \ - with {:?}", - trait_ref, full_env - ); - - // At this point, we already have all of the bounds we need. FulfillmentContext is used - // to store all of the necessary region/lifetime bounds in the InferContext, as well as - // an additional sanity check. - let ocx = ObligationCtxt::new(&infcx); - ocx.register_bound(ObligationCause::dummy(), full_env, ty, trait_did); - let errors = ocx.evaluate_obligations_error_on_ambiguity(); - if !errors.is_empty() { - panic!("Unable to fulfill trait {trait_did:?} for '{ty:?}': {errors:?}"); - } - - let outlives_env = OutlivesEnvironment::new(&infcx, CRATE_DEF_ID, full_env, []); - let _ = infcx.process_registered_region_obligations(&outlives_env, |ty, _| Ok(ty)); - - let region_data = infcx.inner.borrow_mut().unwrap_region_constraints().data().clone(); - - let vid_to_region = self.map_vid_to_region(®ion_data); - - let info = AutoTraitInfo { full_user_env, region_data, vid_to_region }; - - AutoTraitResult::PositiveImpl(auto_trait_callback(info)) - } - - /// The core logic responsible for computing the bounds for our synthesized impl. - /// - /// To calculate the bounds, we call `SelectionContext.select` in a loop. Like - /// `FulfillmentContext`, we recursively select the nested obligations of predicates we - /// encounter. However, whenever we encounter an `UnimplementedError` involving a type - /// parameter, we add it to our `ParamEnv`. Since our goal is to determine when a particular - /// type implements an auto trait, Unimplemented errors tell us what conditions need to be met. - /// - /// This method ends up working somewhat similarly to `FulfillmentContext`, but with a few key - /// differences. `FulfillmentContext` works under the assumption that it's dealing with concrete - /// user code. According, it considers all possible ways that a `Predicate` could be met, which - /// isn't always what we want for a synthesized impl. For example, given the predicate `T: - /// Iterator`, `FulfillmentContext` can end up reporting an Unimplemented error for `T: - /// IntoIterator` -- since there's an implementation of `Iterator` where `T: IntoIterator`, - /// `FulfillmentContext` will drive `SelectionContext` to consider that impl before giving up. - /// If we were to rely on `FulfillmentContext`s decision, we might end up synthesizing an impl - /// like this: - /// ```ignore (illustrative) - /// impl Send for Foo where T: IntoIterator - /// ``` - /// While it might be technically true that Foo implements Send where `T: IntoIterator`, - /// the bound is overly restrictive - it's really only necessary that `T: Iterator`. - /// - /// For this reason, `evaluate_predicates` handles predicates with type variables specially. - /// When we encounter an `Unimplemented` error for a bound such as `T: Iterator`, we immediately - /// add it to our `ParamEnv`, and add it to our stack for recursive evaluation. When we later - /// select it, we'll pick up any nested bounds, without ever inferring that `T: IntoIterator` - /// needs to hold. - /// - /// One additional consideration is supertrait bounds. Normally, a `ParamEnv` is only ever - /// constructed once for a given type. As part of the construction process, the `ParamEnv` will - /// have any supertrait bounds normalized -- e.g., if we have a type `struct Foo`, the - /// `ParamEnv` will contain `T: Copy` and `T: Clone`, since `Copy: Clone`. When we construct our - /// own `ParamEnv`, we need to do this ourselves, through `traits::elaborate`, or - /// else `SelectionContext` will choke on the missing predicates. However, this should never - /// show up in the final synthesized generics: we don't want our generated docs page to contain - /// something like `T: Copy + Clone`, as that's redundant. Therefore, we keep track of a - /// separate `user_env`, which only holds the predicates that will actually be displayed to the - /// user. - fn evaluate_predicates( - &self, - infcx: &InferCtxt<'tcx>, - trait_did: DefId, - ty: Ty<'tcx>, - param_env: ty::ParamEnv<'tcx>, - user_env: ty::ParamEnv<'tcx>, - fresh_preds: &mut FxIndexSet>, - ) -> Option<(ty::ParamEnv<'tcx>, ty::ParamEnv<'tcx>)> { - let tcx = infcx.tcx; - - // Don't try to process any nested obligations involving predicates - // that are already in the `ParamEnv` (modulo regions): we already - // know that they must hold. - for predicate in param_env.caller_bounds() { - fresh_preds.insert(self.clean_pred(infcx, predicate.as_predicate())); - } - - let mut select = SelectionContext::new(infcx); - - let mut already_visited = UnordSet::new(); - let mut predicates = VecDeque::new(); - predicates.push_back(ty::Binder::dummy(ty::TraitPredicate { - trait_ref: ty::TraitRef::new(infcx.tcx, trait_did, [ty]), - - // Auto traits are positive - polarity: ty::PredicatePolarity::Positive, - })); - - let computed_preds = param_env.caller_bounds().iter().map(|c| c.as_predicate()); - let mut user_computed_preds: FxIndexSet<_> = - user_env.caller_bounds().iter().map(|c| c.as_predicate()).collect(); - - let mut new_env = param_env; - let dummy_cause = ObligationCause::dummy(); - - while let Some(pred) = predicates.pop_front() { - if !already_visited.insert(pred) { - continue; - } - - // Call `infcx.resolve_vars_if_possible` to see if we can - // get rid of any inference variables. - let obligation = infcx.resolve_vars_if_possible(Obligation::new( - tcx, - dummy_cause.clone(), - new_env, - pred, - )); - let result = select.poly_select(&obligation); - - match result { - Ok(Some(ref impl_source)) => { - // If we see an explicit negative impl (e.g., `impl !Send for MyStruct`), - // we immediately bail out, since it's impossible for us to continue. - - if let ImplSource::UserDefined(ImplSourceUserDefinedData { - impl_def_id, .. - }) = impl_source - { - // Blame 'tidy' for the weird bracket placement. - if infcx.tcx.impl_polarity(*impl_def_id) != ty::ImplPolarity::Positive { - debug!( - "evaluate_nested_obligations: found explicit negative impl\ - {:?}, bailing out", - impl_def_id - ); - return None; - } - } - - let obligations = impl_source.borrow_nested_obligations().iter().cloned(); - - if !self.evaluate_nested_obligations( - ty, - obligations, - &mut user_computed_preds, - fresh_preds, - &mut predicates, - &mut select, - ) { - return None; - } - } - Ok(None) => {} - Err(SelectionError::Unimplemented) => { - if self.is_param_no_infer(pred.skip_binder().trait_ref.args) { - already_visited.remove(&pred); - self.add_user_pred(&mut user_computed_preds, pred.upcast(self.tcx)); - predicates.push_back(pred); - } else { - debug!( - "evaluate_nested_obligations: `Unimplemented` found, bailing: \ - {:?} {:?} {:?}", - ty, - pred, - pred.skip_binder().trait_ref.args - ); - return None; - } - } - _ => panic!("Unexpected error for '{ty:?}': {result:?}"), - }; - - let normalized_preds = - elaborate(tcx, computed_preds.clone().chain(user_computed_preds.iter().cloned())); - new_env = ty::ParamEnv::new( - tcx.mk_clauses_from_iter(normalized_preds.filter_map(|p| p.as_clause())), - ); - } - - let final_user_env = ty::ParamEnv::new( - tcx.mk_clauses_from_iter(user_computed_preds.into_iter().filter_map(|p| p.as_clause())), - ); - debug!( - "evaluate_nested_obligations(ty={:?}, trait_did={:?}): succeeded with '{:?}' \ - '{:?}'", - ty, trait_did, new_env, final_user_env - ); - - Some((new_env, final_user_env)) - } - - /// This method is designed to work around the following issue: - /// When we compute auto trait bounds, we repeatedly call `SelectionContext.select`, - /// progressively building a `ParamEnv` based on the results we get. - /// However, our usage of `SelectionContext` differs from its normal use within the compiler, - /// in that we capture and re-reprocess predicates from `Unimplemented` errors. - /// - /// This can lead to a corner case when dealing with region parameters. - /// During our selection loop in `evaluate_predicates`, we might end up with - /// two trait predicates that differ only in their region parameters: - /// one containing a HRTB lifetime parameter, and one containing a 'normal' - /// lifetime parameter. For example: - /// ```ignore (illustrative) - /// T as MyTrait<'a> - /// T as MyTrait<'static> - /// ``` - /// If we put both of these predicates in our computed `ParamEnv`, we'll - /// confuse `SelectionContext`, since it will (correctly) view both as being applicable. - /// - /// To solve this, we pick the 'more strict' lifetime bound -- i.e., the HRTB - /// Our end goal is to generate a user-visible description of the conditions - /// under which a type implements an auto trait. A trait predicate involving - /// a HRTB means that the type needs to work with any choice of lifetime, - /// not just one specific lifetime (e.g., `'static`). - fn add_user_pred( - &self, - user_computed_preds: &mut FxIndexSet>, - new_pred: ty::Predicate<'tcx>, - ) { - let mut should_add_new = true; - user_computed_preds.retain(|&old_pred| { - if let ( - ty::PredicateKind::Clause(ty::ClauseKind::Trait(new_trait)), - ty::PredicateKind::Clause(ty::ClauseKind::Trait(old_trait)), - ) = (new_pred.kind().skip_binder(), old_pred.kind().skip_binder()) - { - if new_trait.def_id() == old_trait.def_id() { - let new_args = new_trait.trait_ref.args; - let old_args = old_trait.trait_ref.args; - - if !new_args.types().eq(old_args.types()) { - // We can't compare lifetimes if the types are different, - // so skip checking `old_pred`. - return true; - } - - for (new_region, old_region) in - iter::zip(new_args.regions(), old_args.regions()) - { - match (new_region.kind(), old_region.kind()) { - // If both predicates have an `ReBound` (a HRTB) in the - // same spot, we do nothing. - (ty::ReBound(_, _), ty::ReBound(_, _)) => {} - - (ty::ReBound(_, _), _) | (_, ty::ReVar(_)) => { - // One of these is true: - // The new predicate has a HRTB in a spot where the old - // predicate does not (if they both had a HRTB, the previous - // match arm would have executed). A HRBT is a 'stricter' - // bound than anything else, so we want to keep the newer - // predicate (with the HRBT) in place of the old predicate. - // - // OR - // - // The old predicate has a region variable where the new - // predicate has some other kind of region. An region - // variable isn't something we can actually display to a user, - // so we choose their new predicate (which doesn't have a region - // variable). - // - // In both cases, we want to remove the old predicate, - // from `user_computed_preds`, and replace it with the new - // one. Having both the old and the new - // predicate in a `ParamEnv` would confuse `SelectionContext`. - // - // We're currently in the predicate passed to 'retain', - // so we return `false` to remove the old predicate from - // `user_computed_preds`. - return false; - } - (_, ty::ReBound(_, _)) | (ty::ReVar(_), _) => { - // This is the opposite situation as the previous arm. - // One of these is true: - // - // The old predicate has a HRTB lifetime in a place where the - // new predicate does not. - // - // OR - // - // The new predicate has a region variable where the old - // predicate has some other type of region. - // - // We want to leave the old - // predicate in `user_computed_preds`, and skip adding - // new_pred to `user_computed_params`. - should_add_new = false - } - _ => {} - } - } - } - } - true - }); - - if should_add_new { - user_computed_preds.insert(new_pred); - } - } - - /// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s - /// to each other, we match `ty::RegionVid`s to `ty::Region`s. - fn map_vid_to_region<'cx>( - &self, - regions: &RegionConstraintData<'cx>, - ) -> FxIndexMap> { - let mut vid_map = FxIndexMap::, RegionDeps<'cx>>::default(); - let mut finished_map = FxIndexMap::default(); - - for (c, _) in ®ions.constraints { - match c.kind { - ConstraintKind::VarSubVar => { - let sub_vid = c.sub.as_var(); - let sup_vid = c.sup.as_var(); - { - let deps1 = vid_map.entry(RegionTarget::RegionVid(sub_vid)).or_default(); - deps1.larger.insert(RegionTarget::RegionVid(sup_vid)); - } - - let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default(); - deps2.smaller.insert(RegionTarget::RegionVid(sub_vid)); - } - ConstraintKind::RegSubVar => { - let sup_vid = c.sup.as_var(); - { - let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default(); - deps1.larger.insert(RegionTarget::RegionVid(sup_vid)); - } - - let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default(); - deps2.smaller.insert(RegionTarget::Region(c.sub)); - } - ConstraintKind::VarSubReg => { - let sub_vid = c.sub.as_var(); - finished_map.insert(sub_vid, c.sup); - } - ConstraintKind::RegSubReg => { - { - let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default(); - deps1.larger.insert(RegionTarget::Region(c.sup)); - } - - let deps2 = vid_map.entry(RegionTarget::Region(c.sup)).or_default(); - deps2.smaller.insert(RegionTarget::Region(c.sub)); - } - } - } - - while !vid_map.is_empty() { - let target = *vid_map.keys().next().unwrap(); - let deps = vid_map.swap_remove(&target).unwrap(); - - for smaller in deps.smaller.iter() { - for larger in deps.larger.iter() { - match (smaller, larger) { - (&RegionTarget::Region(_), &RegionTarget::Region(_)) => { - if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) { - let smaller_deps = v.into_mut(); - smaller_deps.larger.insert(*larger); - smaller_deps.larger.swap_remove(&target); - } - - if let IndexEntry::Occupied(v) = vid_map.entry(*larger) { - let larger_deps = v.into_mut(); - larger_deps.smaller.insert(*smaller); - larger_deps.smaller.swap_remove(&target); - } - } - (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => { - finished_map.insert(v1, r1); - } - (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => { - // Do nothing; we don't care about regions that are smaller than vids. - } - (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => { - if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) { - let smaller_deps = v.into_mut(); - smaller_deps.larger.insert(*larger); - smaller_deps.larger.swap_remove(&target); - } - - if let IndexEntry::Occupied(v) = vid_map.entry(*larger) { - let larger_deps = v.into_mut(); - larger_deps.smaller.insert(*smaller); - larger_deps.smaller.swap_remove(&target); - } - } - } - } - } - } - - finished_map - } - - fn is_param_no_infer(&self, args: GenericArgsRef<'tcx>) -> bool { - self.is_of_param(args.type_at(0)) && !args.types().any(|t| t.has_infer_types()) - } - - pub fn is_of_param(&self, ty: Ty<'tcx>) -> bool { - match ty.kind() { - ty::Param(_) => true, - ty::Alias(ty::Projection, p) => self.is_of_param(p.self_ty()), - _ => false, - } - } - - fn is_self_referential_projection(&self, p: ty::PolyProjectionPredicate<'tcx>) -> bool { - if let Some(ty) = p.term().skip_binder().as_type() { - matches!(ty.kind(), ty::Alias(ty::Projection, proj) if proj == &p.skip_binder().projection_term.expect_ty(self.tcx)) - } else { - false - } - } - - fn evaluate_nested_obligations( - &self, - ty: Ty<'_>, - nested: impl Iterator>, - computed_preds: &mut FxIndexSet>, - fresh_preds: &mut FxIndexSet>, - predicates: &mut VecDeque>, - selcx: &mut SelectionContext<'_, 'tcx>, - ) -> bool { - let dummy_cause = ObligationCause::dummy(); - - for obligation in nested { - let is_new_pred = - fresh_preds.insert(self.clean_pred(selcx.infcx, obligation.predicate)); - - // Resolve any inference variables that we can, to help selection succeed - let predicate = selcx.infcx.resolve_vars_if_possible(obligation.predicate); - - // We only add a predicate as a user-displayable bound if - // it involves a generic parameter, and doesn't contain - // any inference variables. - // - // Displaying a bound involving a concrete type (instead of a generic - // parameter) would be pointless, since it's always true - // (e.g. u8: Copy) - // Displaying an inference variable is impossible, since they're - // an internal compiler detail without a defined visual representation - // - // We check this by calling is_of_param on the relevant types - // from the various possible predicates - - let bound_predicate = predicate.kind(); - match bound_predicate.skip_binder() { - ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)) => { - // Add this to `predicates` so that we end up calling `select` - // with it. If this predicate ends up being unimplemented, - // then `evaluate_predicates` will handle adding it the `ParamEnv` - // if possible. - predicates.push_back(bound_predicate.rebind(p)); - } - ty::PredicateKind::Clause(ty::ClauseKind::Projection(p)) => { - let p = bound_predicate.rebind(p); - debug!( - "evaluate_nested_obligations: examining projection predicate {:?}", - predicate - ); - - // As described above, we only want to display - // bounds which include a generic parameter but don't include - // an inference variable. - // Additionally, we check if we've seen this predicate before, - // to avoid rendering duplicate bounds to the user. - if self.is_param_no_infer(p.skip_binder().projection_term.args) - && !p.term().skip_binder().has_infer_types() - && is_new_pred - { - debug!( - "evaluate_nested_obligations: adding projection predicate \ - to computed_preds: {:?}", - predicate - ); - - // Under unusual circumstances, we can end up with a self-referential - // projection predicate. For example: - // ::Value == ::Value - // Not only is displaying this to the user pointless, - // having it in the ParamEnv will cause an issue if we try to call - // poly_project_and_unify_type on the predicate, since this kind of - // predicate will normally never end up in a ParamEnv. - // - // For these reasons, we ignore these weird predicates, - // ensuring that we're able to properly synthesize an auto trait impl - if self.is_self_referential_projection(p) { - debug!( - "evaluate_nested_obligations: encountered a projection - predicate equating a type with itself! Skipping" - ); - } else { - self.add_user_pred(computed_preds, predicate); - } - } - - // There are three possible cases when we project a predicate: - // - // 1. We encounter an error. This means that it's impossible for - // our current type to implement the auto trait - there's bound - // that we could add to our ParamEnv that would 'fix' this kind - // of error, as it's not caused by an unimplemented type. - // - // 2. We successfully project the predicate (Ok(Some(_))), generating - // some subobligations. We then process these subobligations - // like any other generated sub-obligations. - // - // 3. We receive an 'ambiguous' result (Ok(None)) - // If we were actually trying to compile a crate, - // we would need to re-process this obligation later. - // However, all we care about is finding out what bounds - // are needed for our type to implement a particular auto trait. - // We've already added this obligation to our computed ParamEnv - // above (if it was necessary). Therefore, we don't need - // to do any further processing of the obligation. - // - // Note that we *must* try to project *all* projection predicates - // we encounter, even ones without inference variable. - // This ensures that we detect any projection errors, - // which indicate that our type can *never* implement the given - // auto trait. In that case, we will generate an explicit negative - // impl (e.g. 'impl !Send for MyType'). However, we don't - // try to process any of the generated subobligations - - // they contain no new information, since we already know - // that our type implements the projected-through trait, - // and can lead to weird region issues. - // - // Normally, we'll generate a negative impl as a result of encountering - // a type with an explicit negative impl of an auto trait - // (for example, raw pointers have !Send and !Sync impls) - // However, through some **interesting** manipulations of the type - // system, it's actually possible to write a type that never - // implements an auto trait due to a projection error, not a normal - // negative impl error. To properly handle this case, we need - // to ensure that we catch any potential projection errors, - // and turn them into an explicit negative impl for our type. - debug!("Projecting and unifying projection predicate {:?}", predicate); - - match project::poly_project_and_unify_term(selcx, &obligation.with(self.tcx, p)) - { - ProjectAndUnifyResult::MismatchedProjectionTypes(e) => { - debug!( - "evaluate_nested_obligations: Unable to unify predicate \ - '{:?}' '{:?}', bailing out", - ty, e - ); - return false; - } - ProjectAndUnifyResult::Recursive => { - debug!("evaluate_nested_obligations: recursive projection predicate"); - return false; - } - ProjectAndUnifyResult::Holds(v) => { - // We only care about sub-obligations - // when we started out trying to unify - // some inference variables. See the comment above - // for more information - if p.term().skip_binder().has_infer_types() { - if !self.evaluate_nested_obligations( - ty, - v.into_iter(), - computed_preds, - fresh_preds, - predicates, - selcx, - ) { - return false; - } - } - } - ProjectAndUnifyResult::FailedNormalization => { - // It's ok not to make progress when have no inference variables - - // in that case, we were only performing unification to check if an - // error occurred (which would indicate that it's impossible for our - // type to implement the auto trait). - // However, we should always make progress (either by generating - // subobligations or getting an error) when we started off with - // inference variables - if p.term().skip_binder().has_infer_types() { - panic!("Unexpected result when selecting {ty:?} {obligation:?}") - } - } - } - } - ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(binder)) => { - let binder = bound_predicate.rebind(binder); - selcx.infcx.enter_forall(binder, |pred| { - selcx.infcx.register_region_outlives_constraint(pred, &dummy_cause); - }); - } - ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(binder)) => { - let binder = bound_predicate.rebind(binder); - match ( - binder.no_bound_vars(), - binder.map_bound_ref(|pred| pred.0).no_bound_vars(), - ) { - (None, Some(t_a)) => { - selcx.infcx.register_type_outlives_constraint( - t_a, - selcx.infcx.tcx.lifetimes.re_static, - &dummy_cause, - ); - } - (Some(ty::OutlivesPredicate(t_a, r_b)), _) => { - selcx.infcx.register_type_outlives_constraint( - t_a, - r_b, - &dummy_cause, - ); - } - _ => {} - }; - } - ty::PredicateKind::ConstEquate(c1, c2) => { - let evaluate = |c: ty::Const<'tcx>| { - if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() { - let ct = super::try_evaluate_const( - selcx.infcx, - c, - obligation.param_env, - ); - - if let Err(EvaluateConstErr::InvalidConstParamTy(_)) = ct { - self.tcx.dcx().emit_err(UnableToConstructConstantValue { - span: self.tcx.def_span(unevaluated.def), - unevaluated, - }); - } - - ct - } else { - Ok(c) - } - }; - - match (evaluate(c1), evaluate(c2)) { - (Ok(c1), Ok(c2)) => { - match selcx.infcx.at(&obligation.cause, obligation.param_env).eq(DefineOpaqueTypes::Yes,c1, c2) - { - Ok(_) => (), - Err(_) => return false, - } - } - _ => return false, - } - } - - // There's not really much we can do with these predicates - - // we start out with a `ParamEnv` with no inference variables, - // and these don't correspond to adding any new bounds to - // the `ParamEnv`. - ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(..)) - | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..)) - | ty::PredicateKind::NormalizesTo(..) - | ty::PredicateKind::AliasRelate(..) - | ty::PredicateKind::DynCompatible(..) - | ty::PredicateKind::Subtype(..) - // FIXME(generic_const_exprs): you can absolutely add this as a where clauses - | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) - | ty::PredicateKind::Coerce(..) - | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(_)) - | ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(..)) => {} - ty::PredicateKind::Ambiguous => return false, - }; - } - true - } - - pub fn clean_pred( - &self, - infcx: &InferCtxt<'tcx>, - p: ty::Predicate<'tcx>, - ) -> ty::Predicate<'tcx> { - infcx.freshen(p) - } -} diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 308d533e68991..4eec0f23d75fd 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -2,7 +2,6 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html -pub mod auto_trait; pub(crate) mod coherence; pub mod const_evaluatable; mod dyn_compatibility; @@ -71,7 +70,6 @@ pub use self::util::{ upcast_choices, with_replaced_escaping_bound_vars, }; use crate::error_reporting::InferCtxtErrorExt; -use crate::infer::outlives::env::OutlivesEnvironment; use crate::infer::{InferCtxt, TyCtxtInferExt}; use crate::regions::InferCtxtRegionExt; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 6c67916571a40..e9c0de89c89f6 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -1,12 +1,23 @@ +use std::ops::ControlFlow; + use rustc_data_structures::fx::{FxIndexMap, FxIndexSet, IndexEntry}; use rustc_data_structures::thin_vec::ThinVec; +use rustc_data_structures::unord::UnordMap; use rustc_hir as hir; +use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::region_constraints::{ConstraintKind, RegionConstraintData}; -use rustc_middle::bug; -use rustc_middle::ty::{self, Region, Ty, fold_regions}; +use rustc_infer::traits::solve::CandidateSource; +use rustc_middle::traits::solve::Goal; +use rustc_middle::ty::{ + self, Region, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, +}; use rustc_span::def_id::DefId; -use rustc_span::symbol::{Symbol, kw}; -use rustc_trait_selection::traits::auto_trait::{self, RegionTarget}; +use rustc_span::symbol::Symbol; +use rustc_trait_selection::regions::OutlivesEnvironmentBuildExt; +use rustc_trait_selection::solve::inspect::{ + InferCtxtProofTreeExt, InspectGoal, ProbeKind, ProofTreeVisitor, +}; use tracing::{debug, instrument}; use crate::clean::{ @@ -24,7 +35,6 @@ pub(crate) fn synthesize_auto_trait_impls<'tcx>( let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id); let ty = tcx.type_of(item_def_id).instantiate_identity(); - let finder = auto_trait::AutoTraitFinder::new(tcx); let mut auto_trait_impls: Vec<_> = cx .auto_traits .clone() @@ -36,7 +46,6 @@ pub(crate) fn synthesize_auto_trait_impls<'tcx>( trait_def_id, typing_env, item_def_id, - &finder, DiscardPositiveImpls::No, ) }) @@ -50,7 +59,6 @@ pub(crate) fn synthesize_auto_trait_impls<'tcx>( sized_trait_def_id, typing_env, item_def_id, - &finder, DiscardPositiveImpls::Yes, ) { @@ -59,36 +67,36 @@ pub(crate) fn synthesize_auto_trait_impls<'tcx>( auto_trait_impls } -#[instrument(level = "debug", skip(cx, finder))] +#[instrument(level = "debug", skip(cx))] fn synthesize_auto_trait_impl<'tcx>( cx: &mut DocContext<'tcx>, ty: Ty<'tcx>, trait_def_id: DefId, typing_env: ty::TypingEnv<'tcx>, item_def_id: DefId, - finder: &auto_trait::AutoTraitFinder<'tcx>, discard_positive_impls: DiscardPositiveImpls, ) -> Option { let tcx = cx.tcx; - let trait_ref = ty::Binder::dummy(ty::TraitRef::new(tcx, trait_def_id, [ty])); if !cx.generated_synthetics.insert((ty, trait_def_id)) { debug!("already generated, aborting"); return None; } - let result = finder.find_auto_trait_generics(ty, typing_env, trait_def_id, |info| { - clean_param_env(cx, item_def_id, info.full_user_env, info.region_data, info.vid_to_region) - }); + let trait_ref = ty::TraitRef::new(tcx, trait_def_id, [ty]); + + let result = find_auto_trait_generics(tcx, ty, trait_def_id, typing_env); let (generics, polarity) = match result { - auto_trait::AutoTraitResult::PositiveImpl(generics) => { + ImplKind::Positive(info) => { if let DiscardPositiveImpls::Yes = discard_positive_impls { return None; } + let generics = clean_param_env(cx, item_def_id, info); + (generics, ty::ImplPolarity::Positive) } - auto_trait::AutoTraitResult::NegativeImpl => { + ImplKind::Negative => { // For negative impls, we use the generic params, but *not* the predicates, // from the original type. Otherwise, the displayed impl appears to be a // conditional negative impl, when it's really unconditional. @@ -110,7 +118,7 @@ fn synthesize_auto_trait_impl<'tcx>( (generics, ty::ImplPolarity::Negative) } - auto_trait::AutoTraitResult::ExplicitImpl => return None, + ImplKind::Explicit => return None, }; Some(clean::Item { @@ -121,7 +129,11 @@ fn synthesize_auto_trait_impl<'tcx>( kind: clean::ImplItem(Box::new(clean::Impl { safety: hir::Safety::Safe, generics, - trait_: Some(clean_trait_ref_with_constraints(cx, trait_ref, ThinVec::new())), + trait_: Some(clean_trait_ref_with_constraints( + cx, + ty::Binder::dummy(trait_ref), + ThinVec::new(), + )), for_: clean_middle_ty(ty::Binder::dummy(ty), cx, None, None), items: Vec::new(), polarity, @@ -140,64 +152,131 @@ enum DiscardPositiveImpls { No, } -#[instrument(level = "debug", skip(cx, region_data, vid_to_region))] fn clean_param_env<'tcx>( cx: &mut DocContext<'tcx>, item_def_id: DefId, - param_env: ty::ParamEnv<'tcx>, - region_data: RegionConstraintData<'tcx>, - vid_to_region: FxIndexMap>, + info: ImplInfo<'tcx>, ) -> clean::Generics { let tcx = cx.tcx; let generics = tcx.generics_of(item_def_id); - let params: ThinVec<_> = generics + struct InferReplacer<'tcx> { + tcx: TyCtxt<'tcx>, + vid_to_region: FxIndexMap>, + map: FxIndexMap, + } + + impl InferReplacer<'_> { + // FIXME(fmease): Generate nice names that don't clash with existing params. + fn name_for(&mut self, vid: Vid) -> Symbol { + let id = self.map.len(); + *self.map.entry(vid).or_insert_with(|| Symbol::intern(&format!("X{id}"))) + } + } + + impl<'tcx> TypeFolder> for InferReplacer<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { + self.tcx + } + + fn fold_region(&mut self, re: ty::Region<'tcx>) -> ty::Region<'tcx> { + // FIXME(fmease): Maybe add back != ReErased && != ReLateParam assertion? + // FIXME(fmease): We can reach RePlaceholder (cc #120606). How to treat? + let ty::ReVar(vid) = re.kind() else { return re }; + // FIXME(fmease): Generate nice names that don't clash with existing params. + self.vid_to_region.get(&vid).copied().unwrap_or_else(|| { + let id = self.map.len(); + ty::Region::new_early_param( + self.tcx, + ty::EarlyParamRegion { + index: u32::MAX, + name: *self + .map + .entry(Vid::Re(vid)) + .or_insert_with(|| Symbol::intern(&format!("'x{id}"))), + }, + ) + }) + } + + fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { + if !ty.has_infer() { + return ty; + } + let &ty::Infer(ty::InferTy::TyVar(vid)) = ty.kind() else { + return ty.super_fold_with(self); + }; + Ty::new_param(self.tcx, u32::MAX, self.name_for(Vid::Ty(vid))) + } + + fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { + if !ct.has_infer() { + return ct; + } + let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() else { + return ct.super_fold_with(self); + }; + ty::Const::new_param( + self.tcx, + ty::ParamConst::new(u32::MAX, self.name_for(Vid::Ct(vid))), + ) + } + } + + #[derive(PartialEq, Eq, Hash)] + enum Vid { + Ty(ty::TyVid), + Ct(ty::ConstVid), + Re(ty::RegionVid), + } + + let mut replacer = + InferReplacer { tcx, vid_to_region: info.vid_to_region, map: FxIndexMap::default() }; + let preds = info.param_env.caller_bounds().fold_with(&mut replacer); + + let mut params: ThinVec<_> = generics .own_params .iter() - .inspect(|param| { - if cfg!(debug_assertions) { - debug_assert!(!param.is_anonymous_lifetime()); - if let ty::GenericParamDefKind::Type { synthetic, .. } = param.kind { - debug_assert!(!synthetic && param.name != kw::SelfUpper); - } - } - }) // We're basing the generics of the synthetic auto trait impl off of the generics of the // implementing type. Its generic parameters may have defaults, don't copy them over: // Generic parameter defaults are meaningless in impls. .map(|param| clean_generic_param_def(param, clean::ParamDefaults::No, cx)) .collect(); + // FIXME(fmease): Move synthetic lifetime params before type/const params. + params.extend(replacer.map.into_iter().map(|(vid, name)| clean::GenericParamDef { + name, + // FIXME(fmease): Make `GPD.def_id` optional & set it to `None` if possible. + def_id: rustc_hir::def_id::CRATE_DEF_ID.into(), + kind: match vid { + Vid::Ty(_) => clean::GenericParamDefKind::Type { + bounds: ThinVec::new(), + default: None, + synthetic: false, + }, + Vid::Ct(vid) => clean::GenericParamDefKind::Const { + ty: Box::new(clean_middle_ty(info.const_var_tys[&vid], cx, None, None)), + default: None, + }, + Vid::Re(_) => clean::GenericParamDefKind::Lifetime { outlives: ThinVec::new() }, + }, + })); + // FIXME(#111101): Incorporate the explicit predicates of the item here... let item_predicates: FxIndexSet<_> = tcx.param_env(item_def_id).caller_bounds().iter().collect(); - let where_predicates = param_env - .caller_bounds() + let where_predicates = preds .iter() // FIXME: ...which hopefully allows us to simplify this: + // FIXME(fmease): Do the filteriing before InferReplacer? .filter(|pred| { !item_predicates.contains(pred) || pred .as_trait_clause() .is_some_and(|pred| tcx.lang_items().sized_trait() == Some(pred.def_id())) }) - .map(|pred| { - fold_regions(tcx, pred, |r, _| match r.kind() { - // FIXME: Don't `unwrap_or`, I think we should panic if we encounter an infer var that - // we can't map to a concrete region. However, `AutoTraitFinder` *does* leak those kinds - // of `ReVar`s for some reason at the time of writing. See `rustdoc-ui/` tests. - // This is in dire need of an investigation into `AutoTraitFinder`. - ty::ReVar(vid) => vid_to_region.get(&vid).copied().unwrap_or(r), - ty::ReEarlyParam(_) | ty::ReStatic | ty::ReBound(..) | ty::ReError(_) => r, - // FIXME(#120606): `AutoTraitFinder` can actually leak placeholder regions which feels - // incorrect. Needs investigation. - ty::ReLateParam(_) | ty::RePlaceholder(_) | ty::ReErased => { - bug!("unexpected region kind: {r:?}") - } - }) - }) .flat_map(|pred| clean_predicate(pred, cx)) - .chain(clean_region_outlives_constraints(®ion_data, generics)) + .chain(clean_region_outlives_constraints(&info.region_data, generics)) .collect(); let mut generics = clean::Generics { params, where_predicates }; @@ -227,7 +306,7 @@ fn clean_region_outlives_constraints<'tcx>( // This flattening is done in two parts. let mut outlives_predicates = FxIndexMap::<_, Vec<_>>::default(); - let mut map = FxIndexMap::, auto_trait::RegionDeps<'_>>::default(); + let mut map = FxIndexMap::, RegionDeps<'_>>::default(); // (1) We insert all of the constraints into a map. // Each `RegionTarget` (a `RegionVid` or a `Region`) maps to its smaller and larger regions. @@ -371,3 +450,320 @@ fn early_bound_region_name(region: Region<'_>) -> Option { _ => None, } } + +// FIXME(fmease): Rename. +fn find_auto_trait_generics<'tcx>( + tcx: TyCtxt<'tcx>, + self_ty: Ty<'tcx>, + trait_def_id: DefId, + typing_env: ty::TypingEnv<'tcx>, +) -> ImplKind<'tcx> { + let trait_ref = ty::TraitRef::new(tcx, trait_def_id, [self_ty]); + + let (infcx, param_env) = + tcx.infer_ctxt().with_next_trait_solver(true).build_with_typing_env(typing_env); + + for polarity in [ty::PredicatePolarity::Positive, ty::PredicatePolarity::Negative] { + let pred = ty::TraitPredicate { trait_ref, polarity }; + let goal = Goal::new(tcx, param_env, pred); + + // FIXME(fmease): This should most likely happen in a probe. + match infcx.visit_proof_tree(goal, &mut HasUserWrittenImpl) { + ControlFlow::Continue(()) => {} + ControlFlow::Break(()) => return ImplKind::Explicit, + } + } + + let goal = Goal::new(tcx, param_env, trait_ref); + + let mut collector = PredicateCollector { + clauses: typing_env.param_env.caller_bounds().to_vec(), + const_var_tys: UnordMap::default(), + }; + + match infcx.visit_proof_tree(goal, &mut collector) { + ControlFlow::Continue(()) => { + let param_env = ty::ParamEnv::new(tcx.mk_clauses(&collector.clauses)); + + // FIXME(fmease): Decide if we want to keep this. + // if cfg!(debug_assertions) { + // use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; + // let ocx = ObligationCtxt::new(&infcx); + // ocx.register_bound(ObligationCause::dummy(), param_env, self_ty, trait_def_id); + // let errors = ocx.select_all_or_error(); + // if !errors.is_empty() { + // rustc_middle::bug!( + // "synthesized ill-formed auto trait impl of {trait_def_id:?} for `{self_ty}`: {errors:?}" + // ); + // } + // } + + let outlives_env = + OutlivesEnvironment::new(&infcx, hir::def_id::CRATE_DEF_ID, param_env, []); + let _ = infcx.process_registered_region_obligations(&outlives_env, |ty, _| Ok(ty)); + let region_data = infcx.inner.borrow_mut().unwrap_region_constraints().data().clone(); + let vid_to_region = map_vid_to_region(®ion_data); + + ImplKind::Positive(ImplInfo { + param_env, + const_var_tys: collector.const_var_tys, + region_data, + vid_to_region, + }) + } + // FIXME(#146571): Negative impl for !=Sized isn't correct technically speaking. + ControlFlow::Break(()) => ImplKind::Negative, + } +} + +struct HasUserWrittenImpl; + +impl<'tcx> ProofTreeVisitor<'tcx> for HasUserWrittenImpl { + type Result = ControlFlow<()>; + + fn span(&self) -> rustc_span::Span { + rustc_span::DUMMY_SP + } + + fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) -> Self::Result { + for candidate in goal.candidates() { + // Any user-written impl counts even if inapplicable. + if let ProbeKind::TraitCandidate { source: CandidateSource::Impl(_), .. } = + candidate.kind() + { + return ControlFlow::Break(()); + } + } + ControlFlow::Continue(()) + } +} + +struct PredicateCollector<'tcx> { + clauses: Vec>, + const_var_tys: UnordMap>>, +} + +impl<'tcx> PredicateCollector<'tcx> { + fn add(&mut self, goal: Goal<'tcx, ty::Predicate<'tcx>>) { + if let Some(clause) = goal.predicate.as_clause() + && let Some(_) = clause.as_trait_clause() + { + self.clauses.push(clause); + } else { + // FIXME(fmease): Temporary + panic!("can't handle PredicateKind {:?}", goal.predicate) + } + } +} + +// FIXME(fmease): How do deal with ambiguities? +// FIXME(fmease): We do want to collect `` which are ambiguous +// as they can be generated for the projection term. +// FIXME(fmease): Check if we correctly deal with negative impls in the proof tree. +// FIXME(fmease): Check if we correctly deal with higher-ranked goals & candidates. +// FIXME(fmease): Check if we correctly deal with `WellFormed` goals +// FIXME(fmease): Meticulously consider trait pred polarity (`negative_bounds`) +// FIXME(fmease): Check if we correctly deal with overflow / diverging aliases +// FIXME(fmease): Check if we correctly deal with opaque types +impl<'tcx> ProofTreeVisitor<'tcx> for PredicateCollector<'tcx> { + type Result = ControlFlow<()>; + + fn span(&self) -> rustc_span::Span { + rustc_span::DUMMY_SP + } + + fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) -> Self::Result { + let tcx = goal.infcx().tcx; + let predicate = goal.goal().predicate; + + match goal.result() { + Err(_) => {} + result => { + // FIXME(fmease): HACK that's most likely incorrect in general. + if let Ok(ty::solve::Certainty::AMBIGUOUS) = result + && let Some(clause) = predicate.as_clause().map(ty::Clause::kind) + && let ty::ClauseKind::ConstArgHasType(ct, ty) = clause.skip_binder() + && let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() + { + self.const_var_tys.insert(vid, clause.rebind(ty)); + } + + return ControlFlow::Continue(()); + } + } + + let candidates = goal.candidates(); + let candidate = match candidates.as_slice() { + [] => { + // FIXME(fmease): What about outlives-predicates? Shouldn't they not matter here? + if let Some(clause) = predicate.as_clause() + && let ty::ClauseKind::Trait(pred) = clause.kind().skip_binder() + && let ty::Param(_) = pred.self_ty().kind() + { + self.clauses.push(clause); + return ControlFlow::Continue(()); + } + + return ControlFlow::Break(()); + } + [candidate] => candidate, + _ => { + self.add(goal.goal()); + return ControlFlow::Continue(()); + } + }; + + if let Some(clause) = predicate.as_clause() + && let ty::ClauseKind::Projection(pred) = clause.kind().skip_binder() + && let ty::Param(_) = pred.self_ty().kind() + { + self.clauses.push(clause); + return ControlFlow::Continue(()); + } + + // FIXME(fmease): Or should this all happen in a probe? + let nested_goals = candidate.instantiate_nested_goals(self.span()); + + if nested_goals.iter().any(|nested_goal| { + nested_goal + .goal() + .predicate + .as_trait_clause() + .is_some_and(|clause| tcx.is_lang_item(clause.def_id(), hir::LangItem::FnPtrTrait)) + }) { + self.add(goal.goal()); + return ControlFlow::Continue(()); + } + + for nested_goal in nested_goals { + // FIXME(fmease): Make rustc's `visit_with` public & use it here. + if nested_goal.depth() < self.config().max_depth { + self.visit_goal(&nested_goal)?; + } + } + + ControlFlow::Continue(()) + } +} + +/// This is very similar to `handle_lifetimes`. However, instead of matching `ty::Region`s +/// to each other, we match `ty::RegionVid`s to `ty::Region`s. +fn map_vid_to_region<'cx>( + regions: &RegionConstraintData<'cx>, +) -> FxIndexMap> { + let mut vid_map = FxIndexMap::, RegionDeps<'cx>>::default(); + let mut finished_map = FxIndexMap::default(); + + for (c, _) in ®ions.constraints { + match c.kind { + ConstraintKind::VarSubVar => { + let sub_vid = c.sub.as_var(); + let sup_vid = c.sup.as_var(); + { + let deps1 = vid_map.entry(RegionTarget::RegionVid(sub_vid)).or_default(); + deps1.larger.insert(RegionTarget::RegionVid(sup_vid)); + } + + let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default(); + deps2.smaller.insert(RegionTarget::RegionVid(sub_vid)); + } + ConstraintKind::RegSubVar => { + let sup_vid = c.sup.as_var(); + { + let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default(); + deps1.larger.insert(RegionTarget::RegionVid(sup_vid)); + } + + let deps2 = vid_map.entry(RegionTarget::RegionVid(sup_vid)).or_default(); + deps2.smaller.insert(RegionTarget::Region(c.sub)); + } + ConstraintKind::VarSubReg => { + let sub_vid = c.sub.as_var(); + finished_map.insert(sub_vid, c.sup); + } + ConstraintKind::RegSubReg => { + { + let deps1 = vid_map.entry(RegionTarget::Region(c.sub)).or_default(); + deps1.larger.insert(RegionTarget::Region(c.sup)); + } + + let deps2 = vid_map.entry(RegionTarget::Region(c.sup)).or_default(); + deps2.smaller.insert(RegionTarget::Region(c.sub)); + } + } + } + + while !vid_map.is_empty() { + let target = *vid_map.keys().next().unwrap(); + let deps = vid_map.swap_remove(&target).unwrap(); + + for smaller in deps.smaller.iter() { + for larger in deps.larger.iter() { + match (smaller, larger) { + (&RegionTarget::Region(_), &RegionTarget::Region(_)) => { + if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) { + let smaller_deps = v.into_mut(); + smaller_deps.larger.insert(*larger); + smaller_deps.larger.swap_remove(&target); + } + + if let IndexEntry::Occupied(v) = vid_map.entry(*larger) { + let larger_deps = v.into_mut(); + larger_deps.smaller.insert(*smaller); + larger_deps.smaller.swap_remove(&target); + } + } + (&RegionTarget::RegionVid(v1), &RegionTarget::Region(r1)) => { + finished_map.insert(v1, r1); + } + (&RegionTarget::Region(_), &RegionTarget::RegionVid(_)) => { + // Do nothing; we don't care about regions that are smaller than vids. + } + (&RegionTarget::RegionVid(_), &RegionTarget::RegionVid(_)) => { + if let IndexEntry::Occupied(v) = vid_map.entry(*smaller) { + let smaller_deps = v.into_mut(); + smaller_deps.larger.insert(*larger); + smaller_deps.larger.swap_remove(&target); + } + + if let IndexEntry::Occupied(v) = vid_map.entry(*larger) { + let larger_deps = v.into_mut(); + larger_deps.smaller.insert(*smaller); + larger_deps.smaller.swap_remove(&target); + } + } + } + } + } + } + + finished_map +} + +#[derive(Debug)] +struct ImplInfo<'tcx> { + param_env: ty::ParamEnv<'tcx>, + const_var_tys: UnordMap>>, + region_data: RegionConstraintData<'tcx>, + vid_to_region: FxIndexMap>, +} + +#[derive(Debug)] +enum ImplKind<'tcx> { + Explicit, // FIXME: Bad name + Positive(ImplInfo<'tcx>), + Negative, +} + +// FIXME(twk): this is obviously not nice to duplicate like that +#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)] +enum RegionTarget<'tcx> { + Region(Region<'tcx>), + RegionVid(ty::RegionVid), +} + +#[derive(Default, Debug, Clone)] +struct RegionDeps<'tcx> { + larger: FxIndexSet>, + smaller: FxIndexSet>, +}