(almost) Always use ObligationCtxt when dealing with canonical queries

This commit is contained in:
Michael Goulet 2022-10-26 18:00:18 +00:00
parent 0da281b606
commit d793d80cf7
8 changed files with 104 additions and 111 deletions

View file

@ -5,14 +5,14 @@ use rustc_infer::infer::region_constraints::Constraint;
use rustc_infer::infer::region_constraints::RegionConstraintData; use rustc_infer::infer::region_constraints::RegionConstraintData;
use rustc_infer::infer::RegionVariableOrigin; use rustc_infer::infer::RegionVariableOrigin;
use rustc_infer::infer::{InferCtxt, RegionResolutionError, SubregionOrigin, TyCtxtInferExt as _}; use rustc_infer::infer::{InferCtxt, RegionResolutionError, SubregionOrigin, TyCtxtInferExt as _};
use rustc_infer::traits::{Normalized, ObligationCause, TraitEngine, TraitEngineExt}; use rustc_infer::traits::ObligationCause;
use rustc_middle::ty::error::TypeError; use rustc_middle::ty::error::TypeError;
use rustc_middle::ty::RegionVid; use rustc_middle::ty::RegionVid;
use rustc_middle::ty::UniverseIndex; use rustc_middle::ty::UniverseIndex;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
use rustc_span::Span; use rustc_span::Span;
use rustc_trait_selection::traits::query::type_op; use rustc_trait_selection::traits::query::type_op;
use rustc_trait_selection::traits::{SelectionContext, TraitEngineExt as _}; use rustc_trait_selection::traits::ObligationCtxt;
use rustc_traits::{type_op_ascribe_user_type_with_span, type_op_prove_predicate_with_cause}; use rustc_traits::{type_op_ascribe_user_type_with_span, type_op_prove_predicate_with_cause};
use std::fmt; use std::fmt;
@ -240,9 +240,9 @@ impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> {
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> { ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
let (ref infcx, key, _) = let (ref infcx, key, _) =
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query); mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx); let ocx = ObligationCtxt::new(infcx);
type_op_prove_predicate_with_cause(infcx, &mut *fulfill_cx, key, cause); type_op_prove_predicate_with_cause(&ocx, key, cause);
try_extract_error_from_fulfill_cx(fulfill_cx, infcx, placeholder_region, error_region) try_extract_error_from_fulfill_cx(&ocx, placeholder_region, error_region)
} }
} }
@ -281,9 +281,7 @@ where
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> { ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
let (ref infcx, key, _) = let (ref infcx, key, _) =
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query); mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx); let ocx = ObligationCtxt::new(infcx);
let mut selcx = SelectionContext::new(infcx);
// FIXME(lqd): Unify and de-duplicate the following with the actual // FIXME(lqd): Unify and de-duplicate the following with the actual
// `rustc_traits::type_op::type_op_normalize` query to allow the span we need in the // `rustc_traits::type_op::type_op_normalize` query to allow the span we need in the
@ -292,11 +290,9 @@ where
// to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs` test. Check // to normalize the `nll/relate_tys/impl-fn-ignore-binder-via-bottom.rs` test. Check
// after #85499 lands to see if its fixes have erased this difference. // after #85499 lands to see if its fixes have erased this difference.
let (param_env, value) = key.into_parts(); let (param_env, value) = key.into_parts();
let Normalized { value: _, obligations } = let _ = ocx.normalize(cause, param_env, value.value);
rustc_trait_selection::traits::normalize(&mut selcx, param_env, cause, value.value);
fulfill_cx.register_predicate_obligations(infcx, obligations);
try_extract_error_from_fulfill_cx(fulfill_cx, infcx, placeholder_region, error_region) try_extract_error_from_fulfill_cx(&ocx, placeholder_region, error_region)
} }
} }
@ -329,9 +325,9 @@ impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> {
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> { ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
let (ref infcx, key, _) = let (ref infcx, key, _) =
mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query); mbcx.infcx.tcx.infer_ctxt().build_with_canonical(cause.span, &self.canonical_query);
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx); let ocx = ObligationCtxt::new(infcx);
type_op_ascribe_user_type_with_span(infcx, &mut *fulfill_cx, key, Some(cause.span)).ok()?; type_op_ascribe_user_type_with_span(&ocx, key, Some(cause.span)).ok()?;
try_extract_error_from_fulfill_cx(fulfill_cx, infcx, placeholder_region, error_region) try_extract_error_from_fulfill_cx(&ocx, placeholder_region, error_region)
} }
} }
@ -372,25 +368,24 @@ impl<'tcx> TypeOpInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
} }
} }
#[instrument(skip(fulfill_cx, infcx), level = "debug")] #[instrument(skip(ocx), level = "debug")]
fn try_extract_error_from_fulfill_cx<'tcx>( fn try_extract_error_from_fulfill_cx<'tcx>(
mut fulfill_cx: Box<dyn TraitEngine<'tcx> + 'tcx>, ocx: &ObligationCtxt<'_, 'tcx>,
infcx: &InferCtxt<'tcx>,
placeholder_region: ty::Region<'tcx>, placeholder_region: ty::Region<'tcx>,
error_region: Option<ty::Region<'tcx>>, error_region: Option<ty::Region<'tcx>>,
) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> { ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> {
// We generally shouldn't have errors here because the query was // We generally shouldn't have errors here because the query was
// already run, but there's no point using `delay_span_bug` // already run, but there's no point using `delay_span_bug`
// when we're going to emit an error here anyway. // when we're going to emit an error here anyway.
let _errors = fulfill_cx.select_all_or_error(infcx); let _errors = ocx.select_all_or_error();
let region_constraints = infcx.with_region_constraints(|r| r.clone()); let region_constraints = ocx.infcx.with_region_constraints(|r| r.clone());
try_extract_error_from_region_constraints( try_extract_error_from_region_constraints(
infcx, ocx.infcx,
placeholder_region, placeholder_region,
error_region, error_region,
&region_constraints, &region_constraints,
|vid| infcx.region_var_origin(vid), |vid| ocx.infcx.region_var_origin(vid),
|vid| infcx.universe_of_region(infcx.tcx.mk_region(ty::ReVar(vid))), |vid| ocx.infcx.universe_of_region(ocx.infcx.tcx.mk_region(ty::ReVar(vid))),
) )
} }

View file

@ -43,7 +43,7 @@ impl<'tcx> InferCtxt<'tcx> {
/// ///
/// This is only meant to be invoked as part of constructing an /// This is only meant to be invoked as part of constructing an
/// inference context at the start of a query (see /// inference context at the start of a query (see
/// `InferCtxtBuilder::enter_with_canonical`). It basically /// `InferCtxtBuilder::build_with_canonical`). It basically
/// brings the canonical value "into scope" within your new infcx. /// brings the canonical value "into scope" within your new infcx.
/// ///
/// At the end of processing, the substitution S (once /// At the end of processing, the substitution S (once

View file

@ -1,5 +1,5 @@
use crate::traits::query::evaluate_obligation::InferCtxtExt as _; use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
use crate::traits::{self, TraitEngine, TraitEngineExt}; use crate::traits::{self, ObligationCtxt};
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir::lang_items::LangItem; use rustc_hir::lang_items::LangItem;
@ -142,7 +142,7 @@ pub trait InferCtxtBuilderExt<'tcx> {
fn enter_canonical_trait_query<K, R>( fn enter_canonical_trait_query<K, R>(
&mut self, &mut self,
canonical_key: &Canonical<'tcx, K>, canonical_key: &Canonical<'tcx, K>,
operation: impl FnOnce(&InferCtxt<'tcx>, &mut dyn TraitEngine<'tcx>, K) -> Fallible<R>, operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Fallible<R>,
) -> Fallible<CanonicalizedQueryResponse<'tcx, R>> ) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
where where
K: TypeFoldable<'tcx>, K: TypeFoldable<'tcx>,
@ -170,17 +170,17 @@ impl<'tcx> InferCtxtBuilderExt<'tcx> for InferCtxtBuilder<'tcx> {
fn enter_canonical_trait_query<K, R>( fn enter_canonical_trait_query<K, R>(
&mut self, &mut self,
canonical_key: &Canonical<'tcx, K>, canonical_key: &Canonical<'tcx, K>,
operation: impl FnOnce(&InferCtxt<'tcx>, &mut dyn TraitEngine<'tcx>, K) -> Fallible<R>, operation: impl FnOnce(&ObligationCtxt<'_, 'tcx>, K) -> Fallible<R>,
) -> Fallible<CanonicalizedQueryResponse<'tcx, R>> ) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
where where
K: TypeFoldable<'tcx>, K: TypeFoldable<'tcx>,
R: Debug + TypeFoldable<'tcx>, R: Debug + TypeFoldable<'tcx>,
Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>, Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>,
{ {
let (ref infcx, key, canonical_inference_vars) = let (infcx, key, canonical_inference_vars) =
self.build_with_canonical(DUMMY_SP, canonical_key); self.build_with_canonical(DUMMY_SP, canonical_key);
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx); let ocx = ObligationCtxt::new(&infcx);
let value = operation(infcx, &mut *fulfill_cx, key)?; let value = operation(&ocx, key)?;
infcx.make_canonicalized_query_response(canonical_inference_vars, value, &mut *fulfill_cx) ocx.make_canonicalized_query_response(canonical_inference_vars, value)
} }
} }

View file

@ -1,14 +1,20 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::fmt::Debug;
use super::TraitEngine; use super::TraitEngine;
use super::{ChalkFulfillmentContext, FulfillmentContext}; use super::{ChalkFulfillmentContext, FulfillmentContext};
use crate::infer::InferCtxtExt; use crate::infer::InferCtxtExt;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_infer::infer::canonical::{
Canonical, CanonicalVarValues, CanonicalizedQueryResponse, QueryResponse,
};
use rustc_infer::infer::{InferCtxt, InferOk}; use rustc_infer::infer::{InferCtxt, InferOk};
use rustc_infer::traits::query::Fallible;
use rustc_infer::traits::{ use rustc_infer::traits::{
FulfillmentError, Obligation, ObligationCause, PredicateObligation, TraitEngineExt as _, FulfillmentError, Obligation, ObligationCause, PredicateObligation, TraitEngineExt as _,
}; };
use rustc_middle::arena::ArenaAllocatable;
use rustc_middle::ty::error::TypeError; use rustc_middle::ty::error::TypeError;
use rustc_middle::ty::ToPredicate; use rustc_middle::ty::ToPredicate;
use rustc_middle::ty::TypeFoldable; use rustc_middle::ty::TypeFoldable;
@ -154,4 +160,20 @@ impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> {
} }
implied_bounds implied_bounds
} }
pub fn make_canonicalized_query_response<T>(
&self,
inference_vars: CanonicalVarValues<'tcx>,
answer: T,
) -> Fallible<CanonicalizedQueryResponse<'tcx, T>>
where
T: Debug + TypeFoldable<'tcx>,
Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable<'tcx>,
{
self.infcx.make_canonicalized_query_response(
inference_vars,
answer,
&mut **self.engine.borrow_mut(),
)
}
} }

View file

@ -28,9 +28,9 @@ fn implied_outlives_bounds<'tcx>(
&'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>, &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, Vec<OutlivesBound<'tcx>>>>,
NoSolution, NoSolution,
> { > {
tcx.infer_ctxt().enter_canonical_trait_query(&goal, |infcx, _fulfill_cx, key| { tcx.infer_ctxt().enter_canonical_trait_query(&goal, |ocx, key| {
let (param_env, ty) = key.into_parts(); let (param_env, ty) = key.into_parts();
compute_implied_outlives_bounds(&infcx, param_env, ty) compute_implied_outlives_bounds(&ocx.infcx, param_env, ty)
}) })
} }

View file

@ -3,6 +3,7 @@
#![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)] #![deny(rustc::diagnostic_outside_of_impl)]
#![feature(let_chains)]
#![recursion_limit = "256"] #![recursion_limit = "256"]
#[macro_use] #[macro_use]

View file

@ -1,6 +1,5 @@
use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::infer::TyCtxtInferExt;
use rustc_infer::traits::TraitEngineExt as _;
use rustc_middle::ty::query::Providers; use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_middle::ty::{ParamEnvAnd, TyCtxt};
use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::infer::InferCtxtBuilderExt;
@ -23,8 +22,8 @@ fn normalize_projection_ty<'tcx>(
tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed); tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed);
tcx.infer_ctxt().enter_canonical_trait_query( tcx.infer_ctxt().enter_canonical_trait_query(
&goal, &goal,
|infcx, fulfill_cx, ParamEnvAnd { param_env, value: goal }| { |ocx, ParamEnvAnd { param_env, value: goal }| {
let selcx = &mut SelectionContext::new(infcx); let selcx = &mut SelectionContext::new(ocx.infcx);
let cause = ObligationCause::dummy(); let cause = ObligationCause::dummy();
let mut obligations = vec![]; let mut obligations = vec![];
let answer = traits::normalize_projection_type( let answer = traits::normalize_projection_type(
@ -35,7 +34,7 @@ fn normalize_projection_ty<'tcx>(
0, 0,
&mut obligations, &mut obligations,
); );
fulfill_cx.register_predicate_obligations(infcx, obligations); ocx.register_obligations(obligations);
// FIXME(associated_const_equality): All users of normalize_projection_ty expected // FIXME(associated_const_equality): All users of normalize_projection_ty expected
// a type, but there is the possibility it could've been a const now. Maybe change // a type, but there is the possibility it could've been a const now. Maybe change
// it to a Term later? // it to a Term later?

View file

@ -2,17 +2,14 @@ use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_infer::infer::at::ToTrace; use rustc_infer::infer::at::ToTrace;
use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::{DefiningAnchor, InferCtxt, TyCtxtInferExt}; use rustc_infer::infer::{DefiningAnchor, TyCtxtInferExt};
use rustc_infer::traits::{ObligationCauseCode, TraitEngineExt as _}; use rustc_infer::traits::ObligationCauseCode;
use rustc_middle::ty::query::Providers; use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{ use rustc_middle::ty::{self, FnSig, Lift, PolyFnSig, Ty, TyCtxt, TypeFoldable};
self, EarlyBinder, FnSig, Lift, PolyFnSig, Ty, TyCtxt, TypeFoldable, Variance, use rustc_middle::ty::{ParamEnvAnd, Predicate, ToPredicate};
}; use rustc_middle::ty::{UserSelfTy, UserSubsts};
use rustc_middle::ty::{GenericArg, UserSelfTy, UserSubsts};
use rustc_middle::ty::{ParamEnv, ParamEnvAnd, Predicate, ToPredicate};
use rustc_span::{Span, DUMMY_SP}; use rustc_span::{Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::infer::InferCtxtBuilderExt;
use rustc_trait_selection::infer::InferCtxtExt;
use rustc_trait_selection::traits::query::normalize::AtExt; use rustc_trait_selection::traits::query::normalize::AtExt;
use rustc_trait_selection::traits::query::type_op::ascribe_user_type::AscribeUserType; use rustc_trait_selection::traits::query::type_op::ascribe_user_type::AscribeUserType;
use rustc_trait_selection::traits::query::type_op::eq::Eq; use rustc_trait_selection::traits::query::type_op::eq::Eq;
@ -20,7 +17,7 @@ use rustc_trait_selection::traits::query::type_op::normalize::Normalize;
use rustc_trait_selection::traits::query::type_op::prove_predicate::ProvePredicate; use rustc_trait_selection::traits::query::type_op::prove_predicate::ProvePredicate;
use rustc_trait_selection::traits::query::type_op::subtype::Subtype; use rustc_trait_selection::traits::query::type_op::subtype::Subtype;
use rustc_trait_selection::traits::query::{Fallible, NoSolution}; use rustc_trait_selection::traits::query::{Fallible, NoSolution};
use rustc_trait_selection::traits::{Normalized, Obligation, ObligationCause, TraitEngine}; use rustc_trait_selection::traits::{Normalized, Obligation, ObligationCause, ObligationCtxt};
use std::fmt; use std::fmt;
use std::iter::zip; use std::iter::zip;
@ -42,17 +39,16 @@ fn type_op_ascribe_user_type<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, AscribeUserType<'tcx>>>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, AscribeUserType<'tcx>>>,
) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> { ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| { tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |ocx, key| {
type_op_ascribe_user_type_with_span(infcx, fulfill_cx, key, None) type_op_ascribe_user_type_with_span(ocx, key, None)
}) })
} }
/// The core of the `type_op_ascribe_user_type` query: for diagnostics purposes in NLL HRTB errors, /// The core of the `type_op_ascribe_user_type` query: for diagnostics purposes in NLL HRTB errors,
/// this query can be re-run to better track the span of the obligation cause, and improve the error /// this query can be re-run to better track the span of the obligation cause, and improve the error
/// message. Do not call directly unless you're in that very specific context. /// message. Do not call directly unless you're in that very specific context.
pub fn type_op_ascribe_user_type_with_span<'a, 'tcx: 'a>( pub fn type_op_ascribe_user_type_with_span<'tcx>(
infcx: &'a InferCtxt<'tcx>, ocx: &ObligationCtxt<'_, 'tcx>,
fulfill_cx: &'a mut dyn TraitEngine<'tcx>,
key: ParamEnvAnd<'tcx, AscribeUserType<'tcx>>, key: ParamEnvAnd<'tcx, AscribeUserType<'tcx>>,
span: Option<Span>, span: Option<Span>,
) -> Result<(), NoSolution> { ) -> Result<(), NoSolution> {
@ -61,68 +57,55 @@ pub fn type_op_ascribe_user_type_with_span<'a, 'tcx: 'a>(
"type_op_ascribe_user_type: mir_ty={:?} def_id={:?} user_substs={:?}", "type_op_ascribe_user_type: mir_ty={:?} def_id={:?} user_substs={:?}",
mir_ty, def_id, user_substs mir_ty, def_id, user_substs
); );
let cx = AscribeUserTypeCx { ocx, param_env, span: span.unwrap_or(DUMMY_SP) };
let mut cx = AscribeUserTypeCx { infcx, param_env, span: span.unwrap_or(DUMMY_SP), fulfill_cx };
cx.relate_mir_and_user_ty(mir_ty, def_id, user_substs)?; cx.relate_mir_and_user_ty(mir_ty, def_id, user_substs)?;
Ok(()) Ok(())
} }
struct AscribeUserTypeCx<'me, 'tcx> { struct AscribeUserTypeCx<'me, 'tcx> {
infcx: &'me InferCtxt<'tcx>, ocx: &'me ObligationCtxt<'me, 'tcx>,
param_env: ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
span: Span, span: Span,
fulfill_cx: &'me mut dyn TraitEngine<'tcx>,
} }
impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> { impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
fn normalize<T>(&mut self, value: T) -> T fn normalize<T>(&self, value: T) -> T
where where
T: TypeFoldable<'tcx>, T: TypeFoldable<'tcx>,
{ {
self.normalize_with_cause(value, ObligationCause::misc(self.span, hir::CRATE_HIR_ID)) self.normalize_with_cause(value, ObligationCause::misc(self.span, hir::CRATE_HIR_ID))
} }
fn normalize_with_cause<T>(&mut self, value: T, cause: ObligationCause<'tcx>) -> T fn normalize_with_cause<T>(&self, value: T, cause: ObligationCause<'tcx>) -> T
where where
T: TypeFoldable<'tcx>, T: TypeFoldable<'tcx>,
{ {
self.infcx self.ocx.normalize(cause, self.param_env, value)
.partially_normalize_associated_types_in(cause, self.param_env, value)
.into_value_registering_obligations(self.infcx, self.fulfill_cx)
} }
fn relate<T>(&mut self, a: T, variance: Variance, b: T) -> Result<(), NoSolution> fn eq<T>(&self, a: T, b: T) -> Result<(), NoSolution>
where where
T: ToTrace<'tcx>, T: ToTrace<'tcx>,
{ {
self.infcx Ok(self.ocx.register_infer_ok_obligations(
self.ocx
.infcx
.at(&ObligationCause::dummy_with_span(self.span), self.param_env) .at(&ObligationCause::dummy_with_span(self.span), self.param_env)
.relate(a, variance, b)? .eq(a, b)?,
.into_value_registering_obligations(self.infcx, self.fulfill_cx); ))
Ok(())
} }
fn prove_predicate(&mut self, predicate: Predicate<'tcx>, cause: ObligationCause<'tcx>) { fn prove_predicate(&self, predicate: Predicate<'tcx>, cause: ObligationCause<'tcx>) {
self.fulfill_cx.register_predicate_obligation( self.ocx.register_obligation(Obligation::new(cause, self.param_env, predicate));
self.infcx,
Obligation::new(cause, self.param_env, predicate),
);
} }
fn tcx(&self) -> TyCtxt<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> {
self.infcx.tcx self.ocx.infcx.tcx
}
fn subst<T>(&self, value: T, substs: &[GenericArg<'tcx>]) -> T
where
T: TypeFoldable<'tcx>,
{
EarlyBinder(value).subst(self.tcx(), substs)
} }
#[instrument(level = "debug", skip(self))] #[instrument(level = "debug", skip(self))]
fn relate_mir_and_user_ty( fn relate_mir_and_user_ty(
&mut self, &self,
mir_ty: Ty<'tcx>, mir_ty: Ty<'tcx>,
def_id: DefId, def_id: DefId,
user_substs: UserSubsts<'tcx>, user_substs: UserSubsts<'tcx>,
@ -130,20 +113,18 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
let UserSubsts { user_self_ty, substs } = user_substs; let UserSubsts { user_self_ty, substs } = user_substs;
let tcx = self.tcx(); let tcx = self.tcx();
let ty = tcx.type_of(def_id); let ty = tcx.bound_type_of(def_id).subst(tcx, substs);
let ty = self.subst(ty, substs);
let ty = self.normalize(ty); let ty = self.normalize(ty);
debug!("relate_type_and_user_type: ty of def-id is {:?}", ty); debug!("relate_type_and_user_type: ty of def-id is {:?}", ty);
self.relate(mir_ty, Variance::Invariant, ty)?; self.eq(mir_ty, ty)?;
// Prove the predicates coming along with `def_id`. // Prove the predicates coming along with `def_id`.
// //
// Also, normalize the `instantiated_predicates` // Also, normalize the `instantiated_predicates`
// because otherwise we wind up with duplicate "type // because otherwise we wind up with duplicate "type
// outlives" error messages. // outlives" error messages.
let instantiated_predicates = let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
let cause = ObligationCause::dummy_with_span(self.span); let cause = ObligationCause::dummy_with_span(self.span);
@ -163,15 +144,14 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
} }
if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty { if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
let impl_self_ty = self.tcx().type_of(impl_def_id); let impl_self_ty = tcx.bound_type_of(impl_def_id).subst(tcx, substs);
let impl_self_ty = self.subst(impl_self_ty, &substs);
let impl_self_ty = self.normalize(impl_self_ty); let impl_self_ty = self.normalize(impl_self_ty);
self.relate(self_ty, Variance::Invariant, impl_self_ty)?; self.eq(self_ty, impl_self_ty)?;
self.prove_predicate( self.prove_predicate(
ty::Binder::dummy(ty::PredicateKind::WellFormed(impl_self_ty.into())) ty::Binder::dummy(ty::PredicateKind::WellFormed(impl_self_ty.into()))
.to_predicate(self.tcx()), .to_predicate(tcx),
cause.clone(), cause.clone(),
); );
} }
@ -188,7 +168,7 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
// type were ill-formed but did not appear in `ty`, // type were ill-formed but did not appear in `ty`,
// which...could happen with normalization... // which...could happen with normalization...
self.prove_predicate( self.prove_predicate(
ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())).to_predicate(self.tcx()), ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())).to_predicate(tcx),
cause, cause,
); );
Ok(()) Ok(())
@ -199,19 +179,17 @@ fn type_op_eq<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Eq<'tcx>>>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Eq<'tcx>>>,
) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> { ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| { tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |ocx, key| {
let (param_env, Eq { a, b }) = key.into_parts(); let (param_env, Eq { a, b }) = key.into_parts();
infcx ocx.register_infer_ok_obligations(
.at(&ObligationCause::dummy(), param_env) ocx.infcx.at(&ObligationCause::dummy(), param_env).eq(a, b)?,
.eq(a, b)? );
.into_value_registering_obligations(infcx, fulfill_cx);
Ok(()) Ok(())
}) })
} }
fn type_op_normalize<'tcx, T>( fn type_op_normalize<'tcx, T>(
infcx: &InferCtxt<'tcx>, ocx: &ObligationCtxt<'_, 'tcx>,
fulfill_cx: &mut dyn TraitEngine<'tcx>,
key: ParamEnvAnd<'tcx, Normalize<T>>, key: ParamEnvAnd<'tcx, Normalize<T>>,
) -> Fallible<T> ) -> Fallible<T>
where where
@ -219,8 +197,8 @@ where
{ {
let (param_env, Normalize { value }) = key.into_parts(); let (param_env, Normalize { value }) = key.into_parts();
let Normalized { value, obligations } = let Normalized { value, obligations } =
infcx.at(&ObligationCause::dummy(), param_env).normalize(value)?; ocx.infcx.at(&ObligationCause::dummy(), param_env).normalize(value)?;
fulfill_cx.register_predicate_obligations(infcx, obligations); ocx.register_obligations(obligations);
Ok(value) Ok(value)
} }
@ -256,12 +234,11 @@ fn type_op_subtype<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Subtype<'tcx>>>, canonicalized: Canonical<'tcx, ParamEnvAnd<'tcx, Subtype<'tcx>>>,
) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> { ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> {
tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| { tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |ocx, key| {
let (param_env, Subtype { sub, sup }) = key.into_parts(); let (param_env, Subtype { sub, sup }) = key.into_parts();
infcx ocx.register_infer_ok_obligations(
.at(&ObligationCause::dummy(), param_env) ocx.infcx.at(&ObligationCause::dummy(), param_env).sup(sup, sub)?,
.sup(sup, sub)? );
.into_value_registering_obligations(infcx, fulfill_cx);
Ok(()) Ok(())
}) })
} }
@ -274,8 +251,8 @@ fn type_op_prove_predicate<'tcx>(
// impl-trait/issue-99642.rs // impl-trait/issue-99642.rs
tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bubble).enter_canonical_trait_query( tcx.infer_ctxt().with_opaque_type_inference(DefiningAnchor::Bubble).enter_canonical_trait_query(
&canonicalized, &canonicalized,
|infcx, fulfill_cx, key| { |ocx, key| {
type_op_prove_predicate_with_cause(infcx, fulfill_cx, key, ObligationCause::dummy()); type_op_prove_predicate_with_cause(ocx, key, ObligationCause::dummy());
Ok(()) Ok(())
}, },
) )
@ -284,12 +261,11 @@ fn type_op_prove_predicate<'tcx>(
/// The core of the `type_op_prove_predicate` query: for diagnostics purposes in NLL HRTB errors, /// The core of the `type_op_prove_predicate` query: for diagnostics purposes in NLL HRTB errors,
/// this query can be re-run to better track the span of the obligation cause, and improve the error /// this query can be re-run to better track the span of the obligation cause, and improve the error
/// message. Do not call directly unless you're in that very specific context. /// message. Do not call directly unless you're in that very specific context.
pub fn type_op_prove_predicate_with_cause<'a, 'tcx: 'a>( pub fn type_op_prove_predicate_with_cause<'tcx>(
infcx: &'a InferCtxt<'tcx>, ocx: &ObligationCtxt<'_, 'tcx>,
fulfill_cx: &'a mut dyn TraitEngine<'tcx>,
key: ParamEnvAnd<'tcx, ProvePredicate<'tcx>>, key: ParamEnvAnd<'tcx, ProvePredicate<'tcx>>,
cause: ObligationCause<'tcx>, cause: ObligationCause<'tcx>,
) { ) {
let (param_env, ProvePredicate { predicate }) = key.into_parts(); let (param_env, ProvePredicate { predicate }) = key.into_parts();
fulfill_cx.register_predicate_obligation(infcx, Obligation::new(cause, param_env, predicate)); ocx.register_obligation(Obligation::new(cause, param_env, predicate));
} }