always emit AliasRelate
goals when relating aliases
Add `StructurallyRelateAliases` to allow instantiating infer vars with rigid aliases. Change `instantiate_query_response` to be infallible in the new solver. This requires canonicalization to not hide any information used by the query, so weaken universe compression. It also modifies `term_is_fully_unconstrained` to allow region inference variables in a higher universe.
This commit is contained in:
parent
eeeb9b4d31
commit
1b3164f5c9
21 changed files with 417 additions and 272 deletions
|
@ -8,8 +8,9 @@
|
|||
//!
|
||||
//! (1.) If we end up with two rigid aliases, then we relate them structurally.
|
||||
//!
|
||||
//! (2.) If we end up with an infer var and a rigid alias, then
|
||||
//! we assign the alias to the infer var.
|
||||
//! (2.) If we end up with an infer var and a rigid alias, then we instantiate
|
||||
//! the infer var with the constructor of the alias and then recursively relate
|
||||
//! the terms.
|
||||
//!
|
||||
//! (3.) Otherwise, if we end with two rigid (non-projection) or infer types,
|
||||
//! relate them structurally.
|
||||
|
@ -53,22 +54,15 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
}
|
||||
|
||||
(Some(_), None) => {
|
||||
if rhs.is_infer() {
|
||||
self.relate(param_env, lhs, variance, rhs)?;
|
||||
self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
} else {
|
||||
Err(NoSolution)
|
||||
}
|
||||
}
|
||||
(None, Some(_)) => {
|
||||
if lhs.is_infer() {
|
||||
self.relate(param_env, lhs, variance, rhs)?;
|
||||
self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
} else {
|
||||
Err(NoSolution)
|
||||
}
|
||||
(Some(alias), None) => {
|
||||
self.relate_rigid_alias_non_alias(param_env, alias, variance, rhs)
|
||||
}
|
||||
(None, Some(alias)) => self.relate_rigid_alias_non_alias(
|
||||
param_env,
|
||||
alias,
|
||||
variance.xform(ty::Variance::Contravariant),
|
||||
lhs,
|
||||
),
|
||||
|
||||
(Some(alias_lhs), Some(alias_rhs)) => {
|
||||
self.relate(param_env, alias_lhs, variance, alias_rhs)?;
|
||||
|
@ -77,6 +71,39 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Relate a rigid alias with another type. This is the same as
|
||||
/// an ordinary relate except that we treat the outer most alias
|
||||
/// constructor as rigid.
|
||||
#[instrument(level = "debug", skip(self, param_env), ret)]
|
||||
fn relate_rigid_alias_non_alias(
|
||||
&mut self,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
alias: ty::AliasTy<'tcx>,
|
||||
variance: ty::Variance,
|
||||
term: ty::Term<'tcx>,
|
||||
) -> QueryResult<'tcx> {
|
||||
// NOTE: this check is purely an optimization, the structural eq would
|
||||
// always fail if the term is not an inference variable.
|
||||
if term.is_infer() {
|
||||
let tcx = self.tcx();
|
||||
// We need to relate `alias` to `term` treating only the outermost
|
||||
// constructor as rigid, relating any contained generic arguments as
|
||||
// normal. We do this by first structurally equating the `term`
|
||||
// with the alias constructor instantiated with unconstrained infer vars,
|
||||
// and then relate this with the whole `alias`.
|
||||
//
|
||||
// Alternatively we could modify `Equate` for this case by adding another
|
||||
// variant to `StructurallyRelateAliases`.
|
||||
let identity_args = self.fresh_args_for_item(alias.def_id);
|
||||
let rigid_ctor = ty::AliasTy::new(tcx, alias.def_id, identity_args);
|
||||
self.eq_structurally_relating_aliases(param_env, term, rigid_ctor.to_ty(tcx).into())?;
|
||||
self.eq(param_env, alias, rigid_ctor)?;
|
||||
self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
} else {
|
||||
Err(NoSolution)
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: This needs a name that reflects that it's okay to bottom-out with an inference var.
|
||||
/// Normalize the `term` to equate it later.
|
||||
#[instrument(level = "debug", skip(self, param_env), ret)]
|
||||
|
@ -105,6 +132,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self, param_env), ret)]
|
||||
fn try_normalize_ty_recur(
|
||||
&mut self,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
|
@ -128,10 +156,9 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
);
|
||||
this.add_goal(GoalSource::Misc, normalizes_to_goal);
|
||||
this.try_evaluate_added_goals()?;
|
||||
let ty = this.resolve_vars_if_possible(normalized_ty);
|
||||
Ok(this.try_normalize_ty_recur(param_env, depth + 1, ty))
|
||||
Ok(this.resolve_vars_if_possible(normalized_ty))
|
||||
}) {
|
||||
Ok(ty) => ty,
|
||||
Ok(ty) => self.try_normalize_ty_recur(param_env, depth + 1, ty),
|
||||
Err(NoSolution) => Some(ty),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -18,7 +18,7 @@ use rustc_infer::infer::canonical::query_response::make_query_region_constraints
|
|||
use rustc_infer::infer::canonical::CanonicalVarValues;
|
||||
use rustc_infer::infer::canonical::{CanonicalExt, QueryRegionConstraints};
|
||||
use rustc_infer::infer::resolve::EagerResolver;
|
||||
use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk};
|
||||
use rustc_infer::infer::{InferCtxt, InferOk};
|
||||
use rustc_middle::infer::canonical::Canonical;
|
||||
use rustc_middle::traits::query::NoSolution;
|
||||
use rustc_middle::traits::solve::{
|
||||
|
@ -80,7 +80,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
/// the values inferred while solving the instantiated goal.
|
||||
/// - `external_constraints`: additional constraints which aren't expressible
|
||||
/// using simple unification of inference variables.
|
||||
#[instrument(level = "debug", skip(self))]
|
||||
#[instrument(level = "debug", skip(self), ret)]
|
||||
pub(in crate::solve) fn evaluate_added_goals_and_make_canonical_response(
|
||||
&mut self,
|
||||
certainty: Certainty,
|
||||
|
@ -191,7 +191,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
param_env: ty::ParamEnv<'tcx>,
|
||||
original_values: Vec<ty::GenericArg<'tcx>>,
|
||||
response: CanonicalResponse<'tcx>,
|
||||
) -> Result<(Certainty, Vec<Goal<'tcx, ty::Predicate<'tcx>>>), NoSolution> {
|
||||
) -> Certainty {
|
||||
let instantiation = Self::compute_query_response_instantiation_values(
|
||||
self.infcx,
|
||||
&original_values,
|
||||
|
@ -201,15 +201,13 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
let Response { var_values, external_constraints, certainty } =
|
||||
response.instantiate(self.tcx(), &instantiation);
|
||||
|
||||
let nested_goals =
|
||||
Self::unify_query_var_values(self.infcx, param_env, &original_values, var_values)?;
|
||||
Self::unify_query_var_values(self.infcx, param_env, &original_values, var_values);
|
||||
|
||||
let ExternalConstraintsData { region_constraints, opaque_types } =
|
||||
external_constraints.deref();
|
||||
self.register_region_constraints(region_constraints);
|
||||
self.register_opaque_types(param_env, opaque_types)?;
|
||||
|
||||
Ok((certainty, nested_goals))
|
||||
self.register_new_opaque_types(param_env, opaque_types);
|
||||
certainty
|
||||
}
|
||||
|
||||
/// This returns the canoncial variable values to instantiate the bound variables of
|
||||
|
@ -296,32 +294,36 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
CanonicalVarValues { var_values }
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(infcx, param_env), ret)]
|
||||
/// Unify the `original_values` with the `var_values` returned by the canonical query..
|
||||
///
|
||||
/// This assumes that this unification will always succeed. This is the case when
|
||||
/// applying a query response right away. However, calling a canonical query, doing any
|
||||
/// other kind of trait solving, and only then instantiating the result of the query
|
||||
/// can cause the instantiation to fail. This is not supported and we ICE in this case.
|
||||
///
|
||||
/// We always structurally instantiate aliases. Relating aliases needs to be different
|
||||
/// depending on whether the alias is *rigid* or not. We're only really able to tell
|
||||
/// whether an alias is rigid by using the trait solver. When instantiating a response
|
||||
/// from the solver we assume that the solver correctly handled aliases and therefore
|
||||
/// always relate them structurally here.
|
||||
#[instrument(level = "debug", skip(infcx), ret)]
|
||||
fn unify_query_var_values(
|
||||
infcx: &InferCtxt<'tcx>,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
original_values: &[ty::GenericArg<'tcx>],
|
||||
var_values: CanonicalVarValues<'tcx>,
|
||||
) -> Result<Vec<Goal<'tcx, ty::Predicate<'tcx>>>, NoSolution> {
|
||||
) {
|
||||
assert_eq!(original_values.len(), var_values.len());
|
||||
|
||||
let mut nested_goals = vec![];
|
||||
let cause = ObligationCause::dummy();
|
||||
for (&orig, response) in iter::zip(original_values, var_values.var_values) {
|
||||
nested_goals.extend(
|
||||
infcx
|
||||
.at(&ObligationCause::dummy(), param_env)
|
||||
.eq(DefineOpaqueTypes::No, orig, response)
|
||||
.map(|InferOk { value: (), obligations }| {
|
||||
obligations.into_iter().map(|o| Goal::from(o))
|
||||
})
|
||||
.map_err(|e| {
|
||||
debug!(?e, "failed to equate");
|
||||
NoSolution
|
||||
})?,
|
||||
);
|
||||
let InferOk { value: (), obligations } = infcx
|
||||
.at(&cause, param_env)
|
||||
.trace(orig, response)
|
||||
.eq_structurally_relating_aliases(orig, response)
|
||||
.unwrap();
|
||||
assert!(obligations.is_empty());
|
||||
}
|
||||
|
||||
Ok(nested_goals)
|
||||
}
|
||||
|
||||
fn register_region_constraints(&mut self, region_constraints: &QueryRegionConstraints<'tcx>) {
|
||||
|
@ -333,21 +335,17 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
for member_constraint in ®ion_constraints.member_constraints {
|
||||
// FIXME: Deal with member constraints :<
|
||||
let _ = member_constraint;
|
||||
}
|
||||
assert!(region_constraints.member_constraints.is_empty());
|
||||
}
|
||||
|
||||
fn register_opaque_types(
|
||||
fn register_new_opaque_types(
|
||||
&mut self,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
opaque_types: &[(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)],
|
||||
) -> Result<(), NoSolution> {
|
||||
) {
|
||||
for &(key, ty) in opaque_types {
|
||||
self.insert_hidden_type(key, param_env, ty)?;
|
||||
self.insert_hidden_type(key, param_env, ty).unwrap();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -366,19 +364,21 @@ impl<'tcx> inspect::ProofTreeBuilder<'tcx> {
|
|||
)
|
||||
}
|
||||
|
||||
/// Instantiate a `CanonicalState`. This assumes that unifying the var values
|
||||
/// trivially succeeds. Adding any inference constraints which weren't present when
|
||||
/// originally computing the canonical query can result in bugs.
|
||||
pub fn instantiate_canonical_state<T: TypeFoldable<TyCtxt<'tcx>>>(
|
||||
infcx: &InferCtxt<'tcx>,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
original_values: &[ty::GenericArg<'tcx>],
|
||||
state: inspect::CanonicalState<'tcx, T>,
|
||||
) -> Result<(Vec<Goal<'tcx, ty::Predicate<'tcx>>>, T), NoSolution> {
|
||||
) -> T {
|
||||
let instantiation =
|
||||
EvalCtxt::compute_query_response_instantiation_values(infcx, original_values, &state);
|
||||
|
||||
let inspect::State { var_values, data } = state.instantiate(infcx.tcx, &instantiation);
|
||||
|
||||
let nested_goals =
|
||||
EvalCtxt::unify_query_var_values(infcx, param_env, original_values, var_values)?;
|
||||
Ok((nested_goals, data))
|
||||
EvalCtxt::unify_query_var_values(infcx, param_env, original_values, var_values);
|
||||
data
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,8 +17,8 @@ use rustc_middle::traits::solve::{
|
|||
};
|
||||
use rustc_middle::traits::{specialization_graph, DefiningAnchor};
|
||||
use rustc_middle::ty::{
|
||||
self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, TypeVisitable,
|
||||
TypeVisitableExt, TypeVisitor,
|
||||
self, InferCtxtLike, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
|
||||
TypeVisitable, TypeVisitableExt, TypeVisitor,
|
||||
};
|
||||
use rustc_session::config::DumpSolverProofTree;
|
||||
use rustc_span::DUMMY_SP;
|
||||
|
@ -142,10 +142,7 @@ impl<'tcx> InferCtxt<'tcx> {
|
|||
&self,
|
||||
goal: Goal<'tcx, ty::Predicate<'tcx>>,
|
||||
generate_proof_tree: GenerateProofTree,
|
||||
) -> (
|
||||
Result<(bool, Certainty, Vec<Goal<'tcx, ty::Predicate<'tcx>>>), NoSolution>,
|
||||
Option<inspect::GoalEvaluation<'tcx>>,
|
||||
) {
|
||||
) -> (Result<(bool, Certainty), NoSolution>, Option<inspect::GoalEvaluation<'tcx>>) {
|
||||
EvalCtxt::enter_root(self, generate_proof_tree, |ecx| {
|
||||
ecx.evaluate_goal(GoalEvaluationKind::Root, GoalSource::Misc, goal)
|
||||
})
|
||||
|
@ -327,7 +324,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
|
|||
goal_evaluation_kind: GoalEvaluationKind,
|
||||
source: GoalSource,
|
||||
goal: Goal<'tcx, ty::Predicate<'tcx>>,
|
||||
) -> Result<(bool, Certainty, Vec<Goal<'tcx, ty::Predicate<'tcx>>>), NoSolution> {
|
||||
) -> Result<(bool, Certainty), NoSolution> {
|
||||
let (orig_values, canonical_goal) = self.canonicalize_goal(goal);
|
||||
let mut goal_evaluation =
|
||||
self.inspect.new_goal_evaluation(goal, &orig_values, goal_evaluation_kind);
|
||||
|
@ -345,26 +342,13 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
|
|||
Ok(response) => response,
|
||||
};
|
||||
|
||||
let (certainty, has_changed, nested_goals) = match self
|
||||
.instantiate_response_discarding_overflow(
|
||||
goal.param_env,
|
||||
source,
|
||||
orig_values,
|
||||
canonical_response,
|
||||
) {
|
||||
Err(e) => {
|
||||
self.inspect.goal_evaluation(goal_evaluation);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(response) => response,
|
||||
};
|
||||
goal_evaluation.returned_goals(&nested_goals);
|
||||
let (certainty, has_changed) = self.instantiate_response_discarding_overflow(
|
||||
goal.param_env,
|
||||
source,
|
||||
orig_values,
|
||||
canonical_response,
|
||||
);
|
||||
self.inspect.goal_evaluation(goal_evaluation);
|
||||
|
||||
if !has_changed && !nested_goals.is_empty() {
|
||||
bug!("an unchanged goal shouldn't have any side-effects on instantiation");
|
||||
}
|
||||
|
||||
// FIXME: We previously had an assert here that checked that recomputing
|
||||
// a goal after applying its constraints did not change its response.
|
||||
//
|
||||
|
@ -375,7 +359,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
|
|||
// Once we have decided on how to handle trait-system-refactor-initiative#75,
|
||||
// we should re-add an assert here.
|
||||
|
||||
Ok((has_changed, certainty, nested_goals))
|
||||
Ok((has_changed, certainty))
|
||||
}
|
||||
|
||||
fn instantiate_response_discarding_overflow(
|
||||
|
@ -384,7 +368,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
|
|||
source: GoalSource,
|
||||
original_values: Vec<ty::GenericArg<'tcx>>,
|
||||
response: CanonicalResponse<'tcx>,
|
||||
) -> Result<(Certainty, bool, Vec<Goal<'tcx, ty::Predicate<'tcx>>>), NoSolution> {
|
||||
) -> (Certainty, bool) {
|
||||
// The old solver did not evaluate nested goals when normalizing.
|
||||
// It returned the selection constraints allowing a `Projection`
|
||||
// obligation to not hold in coherence while avoiding the fatal error
|
||||
|
@ -405,14 +389,14 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
|
|||
};
|
||||
|
||||
if response.value.certainty == Certainty::OVERFLOW && !keep_overflow_constraints() {
|
||||
Ok((Certainty::OVERFLOW, false, Vec::new()))
|
||||
(Certainty::OVERFLOW, false)
|
||||
} else {
|
||||
let has_changed = !response.value.var_values.is_identity_modulo_regions()
|
||||
|| !response.value.external_constraints.opaque_types.is_empty();
|
||||
|
||||
let (certainty, nested_goals) =
|
||||
self.instantiate_and_apply_query_response(param_env, original_values, response)?;
|
||||
Ok((certainty, has_changed, nested_goals))
|
||||
let certainty =
|
||||
self.instantiate_and_apply_query_response(param_env, original_values, response);
|
||||
(certainty, has_changed)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -537,12 +521,11 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
|
|||
ty::NormalizesTo { alias: goal.predicate.alias, term: unconstrained_rhs },
|
||||
);
|
||||
|
||||
let (_, certainty, instantiate_goals) = self.evaluate_goal(
|
||||
let (_, certainty) = self.evaluate_goal(
|
||||
GoalEvaluationKind::Nested { is_normalizes_to_hack: IsNormalizesToHack::Yes },
|
||||
GoalSource::Misc,
|
||||
unconstrained_goal,
|
||||
)?;
|
||||
self.nested_goals.goals.extend(with_misc_source(instantiate_goals));
|
||||
|
||||
// Finally, equate the goal's RHS with the unconstrained var.
|
||||
// We put the nested goals from this into goals instead of
|
||||
|
@ -573,12 +556,11 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
|
|||
}
|
||||
|
||||
for (source, goal) in goals.goals.drain(..) {
|
||||
let (has_changed, certainty, instantiate_goals) = self.evaluate_goal(
|
||||
let (has_changed, certainty) = self.evaluate_goal(
|
||||
GoalEvaluationKind::Nested { is_normalizes_to_hack: IsNormalizesToHack::No },
|
||||
source,
|
||||
goal,
|
||||
)?;
|
||||
self.nested_goals.goals.extend(with_misc_source(instantiate_goals));
|
||||
if has_changed {
|
||||
unchanged_certainty = None;
|
||||
}
|
||||
|
@ -633,43 +615,46 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
&self,
|
||||
goal: Goal<'tcx, ty::NormalizesTo<'tcx>>,
|
||||
) -> bool {
|
||||
let term_is_infer = match goal.predicate.term.unpack() {
|
||||
let universe_of_term = match goal.predicate.term.unpack() {
|
||||
ty::TermKind::Ty(ty) => {
|
||||
if let &ty::Infer(ty::TyVar(vid)) = ty.kind() {
|
||||
match self.infcx.probe_ty_var(vid) {
|
||||
Ok(value) => bug!("resolved var in query: {goal:?} {value:?}"),
|
||||
Err(universe) => universe == self.infcx.universe(),
|
||||
}
|
||||
self.infcx.universe_of_ty(vid).unwrap()
|
||||
} else {
|
||||
false
|
||||
return false;
|
||||
}
|
||||
}
|
||||
ty::TermKind::Const(ct) => {
|
||||
if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
|
||||
match self.infcx.probe_const_var(vid) {
|
||||
Ok(value) => bug!("resolved var in query: {goal:?} {value:?}"),
|
||||
Err(universe) => universe == self.infcx.universe(),
|
||||
}
|
||||
self.infcx.universe_of_ct(vid).unwrap()
|
||||
} else {
|
||||
false
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Guard against `<T as Trait<?0>>::Assoc = ?0>`.
|
||||
struct ContainsTerm<'a, 'tcx> {
|
||||
struct ContainsTermOrNotNameable<'a, 'tcx> {
|
||||
term: ty::Term<'tcx>,
|
||||
universe_of_term: ty::UniverseIndex,
|
||||
infcx: &'a InferCtxt<'tcx>,
|
||||
}
|
||||
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTerm<'_, 'tcx> {
|
||||
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ContainsTermOrNotNameable<'_, 'tcx> {
|
||||
type BreakTy = ();
|
||||
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
|
||||
if let Some(vid) = t.ty_vid()
|
||||
&& let ty::TermKind::Ty(term) = self.term.unpack()
|
||||
&& let Some(term_vid) = term.ty_vid()
|
||||
&& self.infcx.root_var(vid) == self.infcx.root_var(term_vid)
|
||||
{
|
||||
ControlFlow::Break(())
|
||||
if let Some(vid) = t.ty_vid() {
|
||||
if let ty::TermKind::Ty(term) = self.term.unpack()
|
||||
&& let Some(term_vid) = term.ty_vid()
|
||||
&& self.infcx.root_var(vid) == self.infcx.root_var(term_vid)
|
||||
{
|
||||
ControlFlow::Break(())
|
||||
} else if self
|
||||
.universe_of_term
|
||||
.cannot_name(self.infcx.universe_of_ty(vid).unwrap())
|
||||
{
|
||||
ControlFlow::Break(())
|
||||
} else {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
} else if t.has_non_region_infer() {
|
||||
t.super_visit_with(self)
|
||||
} else {
|
||||
|
@ -678,12 +663,20 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
}
|
||||
|
||||
fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
|
||||
if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = c.kind()
|
||||
&& let ty::TermKind::Const(term) = self.term.unpack()
|
||||
&& let ty::ConstKind::Infer(ty::InferConst::Var(term_vid)) = term.kind()
|
||||
&& self.infcx.root_const_var(vid) == self.infcx.root_const_var(term_vid)
|
||||
{
|
||||
ControlFlow::Break(())
|
||||
if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = c.kind() {
|
||||
if let ty::TermKind::Const(term) = self.term.unpack()
|
||||
&& let ty::ConstKind::Infer(ty::InferConst::Var(term_vid)) = term.kind()
|
||||
&& self.infcx.root_const_var(vid) == self.infcx.root_const_var(term_vid)
|
||||
{
|
||||
ControlFlow::Break(())
|
||||
} else if self
|
||||
.universe_of_term
|
||||
.cannot_name(self.infcx.universe_of_ct(vid).unwrap())
|
||||
{
|
||||
ControlFlow::Break(())
|
||||
} else {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
} else if c.has_non_region_infer() {
|
||||
c.super_visit_with(self)
|
||||
} else {
|
||||
|
@ -692,10 +685,12 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
let mut visitor = ContainsTerm { infcx: self.infcx, term: goal.predicate.term };
|
||||
|
||||
term_is_infer
|
||||
&& goal.predicate.alias.visit_with(&mut visitor).is_continue()
|
||||
let mut visitor = ContainsTermOrNotNameable {
|
||||
infcx: self.infcx,
|
||||
universe_of_term,
|
||||
term: goal.predicate.term,
|
||||
};
|
||||
goal.predicate.alias.visit_with(&mut visitor).is_continue()
|
||||
&& goal.param_env.visit_with(&mut visitor).is_continue()
|
||||
}
|
||||
|
||||
|
@ -718,6 +713,26 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
})
|
||||
}
|
||||
|
||||
/// This sohuld only be used when we're either instantiating a previously
|
||||
/// unconstrained "return value" or when we're sure that all aliases in
|
||||
/// the types are rigid.
|
||||
#[instrument(level = "debug", skip(self, param_env), ret)]
|
||||
pub(super) fn eq_structurally_relating_aliases<T: ToTrace<'tcx>>(
|
||||
&mut self,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
lhs: T,
|
||||
rhs: T,
|
||||
) -> Result<(), NoSolution> {
|
||||
let cause = ObligationCause::dummy();
|
||||
let InferOk { value: (), obligations } = self
|
||||
.infcx
|
||||
.at(&cause, param_env)
|
||||
.trace(lhs, rhs)
|
||||
.eq_structurally_relating_aliases(lhs, rhs)?;
|
||||
assert!(obligations.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self, param_env), ret)]
|
||||
pub(super) fn sub<T: ToTrace<'tcx>>(
|
||||
&mut self,
|
||||
|
|
|
@ -58,44 +58,26 @@ impl<'tcx> InferCtxt<'tcx> {
|
|||
}
|
||||
|
||||
let candidate = candidates.pop().unwrap();
|
||||
let (certainty, nested_goals) = ecx
|
||||
.instantiate_and_apply_query_response(
|
||||
trait_goal.param_env,
|
||||
orig_values,
|
||||
candidate.result,
|
||||
)
|
||||
.map_err(|_| SelectionError::Unimplemented)?;
|
||||
let certainty = ecx.instantiate_and_apply_query_response(
|
||||
trait_goal.param_env,
|
||||
orig_values,
|
||||
candidate.result,
|
||||
);
|
||||
|
||||
Ok(Some((candidate, certainty, nested_goals)))
|
||||
Ok(Some((candidate, certainty)))
|
||||
});
|
||||
|
||||
let (candidate, certainty, nested_goals) = match result {
|
||||
Ok(Some((candidate, certainty, nested_goals))) => {
|
||||
(candidate, certainty, nested_goals)
|
||||
}
|
||||
let (candidate, certainty) = match result {
|
||||
Ok(Some(result)) => result,
|
||||
Ok(None) => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
let nested_obligations: Vec<_> = nested_goals
|
||||
.into_iter()
|
||||
.map(|goal| {
|
||||
Obligation::new(
|
||||
self.tcx,
|
||||
ObligationCause::dummy(),
|
||||
goal.param_env,
|
||||
goal.predicate,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let goal = self.resolve_vars_if_possible(trait_goal);
|
||||
match (certainty, candidate.source) {
|
||||
// Rematching the implementation will instantiate the same nested goals that
|
||||
// would have caused the ambiguity, so we can still make progress here regardless.
|
||||
(_, CandidateSource::Impl(def_id)) => {
|
||||
rematch_impl(self, goal, def_id, nested_obligations)
|
||||
}
|
||||
(_, CandidateSource::Impl(def_id)) => rematch_impl(self, goal, def_id),
|
||||
|
||||
// If an unsize goal is ambiguous, then we can manually rematch it to make
|
||||
// selection progress for coercion during HIR typeck. If it is *not* ambiguous,
|
||||
|
@ -108,20 +90,20 @@ impl<'tcx> InferCtxt<'tcx> {
|
|||
| (Certainty::Yes, CandidateSource::BuiltinImpl(src @ BuiltinImplSource::Misc))
|
||||
if self.tcx.lang_items().unsize_trait() == Some(goal.predicate.def_id()) =>
|
||||
{
|
||||
rematch_unsize(self, goal, nested_obligations, src, certainty)
|
||||
rematch_unsize(self, goal, src, certainty)
|
||||
}
|
||||
|
||||
// Technically some builtin impls have nested obligations, but if
|
||||
// `Certainty::Yes`, then they should've all been verified and don't
|
||||
// need re-checking.
|
||||
(Certainty::Yes, CandidateSource::BuiltinImpl(src)) => {
|
||||
Ok(Some(ImplSource::Builtin(src, nested_obligations)))
|
||||
Ok(Some(ImplSource::Builtin(src, vec![])))
|
||||
}
|
||||
|
||||
// It's fine not to do anything to rematch these, since there are no
|
||||
// nested obligations.
|
||||
(Certainty::Yes, CandidateSource::ParamEnv(_) | CandidateSource::AliasBound) => {
|
||||
Ok(Some(ImplSource::Param(nested_obligations)))
|
||||
Ok(Some(ImplSource::Param(vec![])))
|
||||
}
|
||||
|
||||
(Certainty::Maybe(_), _) => Ok(None),
|
||||
|
@ -192,19 +174,16 @@ fn rematch_impl<'tcx>(
|
|||
infcx: &InferCtxt<'tcx>,
|
||||
goal: Goal<'tcx, ty::TraitPredicate<'tcx>>,
|
||||
impl_def_id: DefId,
|
||||
mut nested: Vec<PredicateObligation<'tcx>>,
|
||||
) -> SelectionResult<'tcx, Selection<'tcx>> {
|
||||
let args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
|
||||
let impl_trait_ref =
|
||||
infcx.tcx.impl_trait_ref(impl_def_id).unwrap().instantiate(infcx.tcx, args);
|
||||
|
||||
nested.extend(
|
||||
infcx
|
||||
.at(&ObligationCause::dummy(), goal.param_env)
|
||||
.eq(DefineOpaqueTypes::No, goal.predicate.trait_ref, impl_trait_ref)
|
||||
.map_err(|_| SelectionError::Unimplemented)?
|
||||
.into_obligations(),
|
||||
);
|
||||
let mut nested = infcx
|
||||
.at(&ObligationCause::dummy(), goal.param_env)
|
||||
.eq(DefineOpaqueTypes::No, goal.predicate.trait_ref, impl_trait_ref)
|
||||
.map_err(|_| SelectionError::Unimplemented)?
|
||||
.into_obligations();
|
||||
|
||||
nested.extend(
|
||||
infcx.tcx.predicates_of(impl_def_id).instantiate(infcx.tcx, args).into_iter().map(
|
||||
|
@ -221,11 +200,11 @@ fn rematch_impl<'tcx>(
|
|||
fn rematch_unsize<'tcx>(
|
||||
infcx: &InferCtxt<'tcx>,
|
||||
goal: Goal<'tcx, ty::TraitPredicate<'tcx>>,
|
||||
mut nested: Vec<PredicateObligation<'tcx>>,
|
||||
source: BuiltinImplSource,
|
||||
certainty: Certainty,
|
||||
) -> SelectionResult<'tcx, Selection<'tcx>> {
|
||||
let tcx = infcx.tcx;
|
||||
let mut nested = vec![];
|
||||
let a_ty = structurally_normalize(goal.predicate.self_ty(), infcx, goal.param_env, &mut nested);
|
||||
let b_ty = structurally_normalize(
|
||||
goal.predicate.trait_ref.args.type_at(1),
|
||||
|
|
|
@ -2,7 +2,6 @@ use std::mem;
|
|||
|
||||
use rustc_infer::infer::InferCtxt;
|
||||
use rustc_infer::traits::solve::MaybeCause;
|
||||
use rustc_infer::traits::Obligation;
|
||||
use rustc_infer::traits::{
|
||||
query::NoSolution, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes,
|
||||
PredicateObligation, SelectionError, TraitEngine,
|
||||
|
@ -11,7 +10,7 @@ use rustc_middle::ty;
|
|||
use rustc_middle::ty::error::{ExpectedFound, TypeError};
|
||||
|
||||
use super::eval_ctxt::GenerateProofTree;
|
||||
use super::{Certainty, Goal, InferCtxtEvalExt};
|
||||
use super::{Certainty, InferCtxtEvalExt};
|
||||
|
||||
/// A trait engine using the new trait solver.
|
||||
///
|
||||
|
@ -48,11 +47,11 @@ impl<'tcx> FulfillmentCtxt<'tcx> {
|
|||
&self,
|
||||
infcx: &InferCtxt<'tcx>,
|
||||
obligation: &PredicateObligation<'tcx>,
|
||||
result: &Result<(bool, Certainty, Vec<Goal<'tcx, ty::Predicate<'tcx>>>), NoSolution>,
|
||||
result: &Result<(bool, Certainty), NoSolution>,
|
||||
) {
|
||||
if let Some(inspector) = infcx.obligation_inspector.get() {
|
||||
let result = match result {
|
||||
Ok((_, c, _)) => Ok(*c),
|
||||
Ok((_, c)) => Ok(*c),
|
||||
Err(NoSolution) => Err(NoSolution),
|
||||
};
|
||||
(inspector)(infcx, &obligation, result);
|
||||
|
@ -80,13 +79,13 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> {
|
|||
.evaluate_root_goal(obligation.clone().into(), GenerateProofTree::IfEnabled)
|
||||
.0
|
||||
{
|
||||
Ok((_, Certainty::Maybe(MaybeCause::Ambiguity), _)) => {
|
||||
Ok((_, Certainty::Maybe(MaybeCause::Ambiguity))) => {
|
||||
FulfillmentErrorCode::Ambiguity { overflow: false }
|
||||
}
|
||||
Ok((_, Certainty::Maybe(MaybeCause::Overflow), _)) => {
|
||||
Ok((_, Certainty::Maybe(MaybeCause::Overflow))) => {
|
||||
FulfillmentErrorCode::Ambiguity { overflow: true }
|
||||
}
|
||||
Ok((_, Certainty::Yes, _)) => {
|
||||
Ok((_, Certainty::Yes)) => {
|
||||
bug!("did not expect successful goal when collecting ambiguity errors")
|
||||
}
|
||||
Err(_) => {
|
||||
|
@ -120,7 +119,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> {
|
|||
let goal = obligation.clone().into();
|
||||
let result = infcx.evaluate_root_goal(goal, GenerateProofTree::IfEnabled).0;
|
||||
self.inspect_evaluated_obligation(infcx, &obligation, &result);
|
||||
let (changed, certainty, nested_goals) = match result {
|
||||
let (changed, certainty) = match result {
|
||||
Ok(result) => result,
|
||||
Err(NoSolution) => {
|
||||
errors.push(FulfillmentError {
|
||||
|
@ -178,16 +177,6 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> {
|
|||
continue;
|
||||
}
|
||||
};
|
||||
// Push any nested goals that we get from unifying our canonical response
|
||||
// with our obligation onto the fulfillment context.
|
||||
self.obligations.extend(nested_goals.into_iter().map(|goal| {
|
||||
Obligation::new(
|
||||
infcx.tcx,
|
||||
obligation.cause.clone(),
|
||||
goal.param_env,
|
||||
goal.predicate,
|
||||
)
|
||||
}));
|
||||
has_changed |= changed;
|
||||
match certainty {
|
||||
Certainty::Yes => {}
|
||||
|
|
|
@ -63,21 +63,12 @@ impl<'a, 'tcx> InspectCandidate<'a, 'tcx> {
|
|||
infcx.probe(|_| {
|
||||
let mut instantiated_goals = vec![];
|
||||
for goal in &self.nested_goals {
|
||||
let goal = match ProofTreeBuilder::instantiate_canonical_state(
|
||||
let goal = ProofTreeBuilder::instantiate_canonical_state(
|
||||
infcx,
|
||||
self.goal.goal.param_env,
|
||||
self.goal.orig_values,
|
||||
*goal,
|
||||
) {
|
||||
Ok((_goals, goal)) => goal,
|
||||
Err(NoSolution) => {
|
||||
warn!(
|
||||
"unexpected failure when instantiating {:?}: {:?}",
|
||||
goal, self.nested_goals
|
||||
);
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
};
|
||||
);
|
||||
instantiated_goals.push(goal);
|
||||
}
|
||||
|
||||
|
|
|
@ -87,7 +87,6 @@ struct WipGoalEvaluation<'tcx> {
|
|||
pub uncanonicalized_goal: Goal<'tcx, ty::Predicate<'tcx>>,
|
||||
pub kind: WipGoalEvaluationKind<'tcx>,
|
||||
pub evaluation: Option<WipCanonicalGoalEvaluation<'tcx>>,
|
||||
pub returned_goals: Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
|
||||
}
|
||||
|
||||
impl<'tcx> WipGoalEvaluation<'tcx> {
|
||||
|
@ -103,7 +102,6 @@ impl<'tcx> WipGoalEvaluation<'tcx> {
|
|||
}
|
||||
},
|
||||
evaluation: self.evaluation.unwrap().finalize(),
|
||||
returned_goals: self.returned_goals,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -312,7 +310,6 @@ impl<'tcx> ProofTreeBuilder<'tcx> {
|
|||
}
|
||||
},
|
||||
evaluation: None,
|
||||
returned_goals: vec![],
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -369,17 +366,6 @@ impl<'tcx> ProofTreeBuilder<'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn returned_goals(&mut self, goals: &[Goal<'tcx, ty::Predicate<'tcx>>]) {
|
||||
if let Some(this) = self.as_mut() {
|
||||
match this {
|
||||
DebugSolver::GoalEvaluation(evaluation) => {
|
||||
assert!(evaluation.returned_goals.is_empty());
|
||||
evaluation.returned_goals.extend(goals);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn goal_evaluation(&mut self, goal_evaluation: ProofTreeBuilder<'tcx>) {
|
||||
if let Some(this) = self.as_mut() {
|
||||
match (this, *goal_evaluation.state.unwrap()) {
|
||||
|
|
|
@ -68,6 +68,34 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
|
|||
kind => bug!("unknown DefKind {} in projection goal: {goal:#?}", kind.descr(def_id)),
|
||||
}
|
||||
}
|
||||
|
||||
/// When normalizing an associated item, constrain the result to `term`.
|
||||
///
|
||||
/// While `NormalizesTo` goals have the normalized-to term as an argument,
|
||||
/// this argument is always fully unconstrained for associated items.
|
||||
/// It is therefore appropriate to instead think of these `NormalizesTo` goals
|
||||
/// as function returning a term after normalizing.
|
||||
///
|
||||
/// When equating an inference variable and an alias, we tend to emit `alias-relate`
|
||||
/// goals and only actually instantiate the inference variable with an alias if the
|
||||
/// alias is rigid. However, this means that constraining the expected term of
|
||||
/// such goals ends up fully structurally normalizing the resulting type instead of
|
||||
/// only by one step. To avoid this we instead use structural equality here, resulting
|
||||
/// in each `NormalizesTo` only projects by a single step.
|
||||
///
|
||||
/// Not doing so, currently causes issues because trying to normalize an opaque type
|
||||
/// during alias-relate doesn't actually constrain the opaque if the concrete type
|
||||
/// is an inference variable. This means that `NormalizesTo` for associated types
|
||||
/// normalizing to an opaque type always resulted in ambiguity, breaking tests e.g.
|
||||
/// tests/ui/type-alias-impl-trait/issue-78450.rs.
|
||||
pub fn instantiate_normalizes_to_term(
|
||||
&mut self,
|
||||
goal: Goal<'tcx, NormalizesTo<'tcx>>,
|
||||
term: ty::Term<'tcx>,
|
||||
) {
|
||||
self.eq_structurally_relating_aliases(goal.param_env, goal.predicate.term, term)
|
||||
.expect("expected goal term to be fully unconstrained");
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> {
|
||||
|
@ -104,8 +132,8 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> {
|
|||
goal.predicate.alias,
|
||||
assumption_projection_pred.projection_ty,
|
||||
)?;
|
||||
ecx.eq(goal.param_env, goal.predicate.term, assumption_projection_pred.term)
|
||||
.expect("expected goal term to be fully unconstrained");
|
||||
|
||||
ecx.instantiate_normalizes_to_term(goal, assumption_projection_pred.term);
|
||||
|
||||
// Add GAT where clauses from the trait's definition
|
||||
ecx.add_goals(
|
||||
|
@ -192,8 +220,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> {
|
|||
"cannot project to an associated function"
|
||||
),
|
||||
};
|
||||
ecx.eq(goal.param_env, goal.predicate.term, error_term)
|
||||
.expect("expected goal term to be fully unconstrained");
|
||||
ecx.instantiate_normalizes_to_term(goal, error_term);
|
||||
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
};
|
||||
|
||||
|
@ -248,8 +275,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> {
|
|||
ty::AssocKind::Fn => unreachable!("we should never project to a fn"),
|
||||
};
|
||||
|
||||
ecx.eq(goal.param_env, goal.predicate.term, term.instantiate(tcx, args))
|
||||
.expect("expected goal term to be fully unconstrained");
|
||||
ecx.instantiate_normalizes_to_term(goal, term.instantiate(tcx, args));
|
||||
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
})
|
||||
}
|
||||
|
@ -456,7 +482,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> {
|
|||
borrow_region.expect_region(),
|
||||
);
|
||||
|
||||
ecx.eq(goal.param_env, goal.predicate.term.ty().unwrap(), upvars_ty)?;
|
||||
ecx.instantiate_normalizes_to_term(goal, upvars_ty.into());
|
||||
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
}
|
||||
|
||||
|
@ -543,8 +569,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> {
|
|||
),
|
||||
};
|
||||
|
||||
ecx.eq(goal.param_env, goal.predicate.term, metadata_ty.into())
|
||||
.expect("expected goal term to be fully unconstrained");
|
||||
ecx.instantiate_normalizes_to_term(goal, metadata_ty.into());
|
||||
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
})
|
||||
}
|
||||
|
@ -627,20 +652,22 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> {
|
|||
}
|
||||
|
||||
ecx.probe_misc_candidate("builtin AsyncIterator kind").enter(|ecx| {
|
||||
let expected_ty = ecx.next_ty_infer();
|
||||
// Take `AsyncIterator<Item = I>` and turn it into the corresponding
|
||||
// coroutine yield ty `Poll<Option<I>>`.
|
||||
let expected_ty = Ty::new_adt(
|
||||
let wrapped_expected_ty = Ty::new_adt(
|
||||
tcx,
|
||||
tcx.adt_def(tcx.require_lang_item(LangItem::Poll, None)),
|
||||
tcx.mk_args(&[Ty::new_adt(
|
||||
tcx,
|
||||
tcx.adt_def(tcx.require_lang_item(LangItem::Option, None)),
|
||||
tcx.mk_args(&[goal.predicate.term.into()]),
|
||||
tcx.mk_args(&[expected_ty.into()]),
|
||||
)
|
||||
.into()]),
|
||||
);
|
||||
let yield_ty = args.as_coroutine().yield_ty();
|
||||
ecx.eq(goal.param_env, expected_ty, yield_ty)?;
|
||||
ecx.eq(goal.param_env, wrapped_expected_ty, yield_ty)?;
|
||||
ecx.instantiate_normalizes_to_term(goal, expected_ty.into());
|
||||
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
})
|
||||
}
|
||||
|
@ -742,8 +769,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> {
|
|||
};
|
||||
|
||||
ecx.probe_misc_candidate("builtin discriminant kind").enter(|ecx| {
|
||||
ecx.eq(goal.param_env, goal.predicate.term, discriminant_ty.into())
|
||||
.expect("expected goal term to be fully unconstrained");
|
||||
ecx.instantiate_normalizes_to_term(goal, discriminant_ty.into());
|
||||
ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue