Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement some candidates for the new solver (redux) #107004

Merged
merged 7 commits into from
Jan 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2382,6 +2382,11 @@ impl<'tcx> TyCtxt<'tcx> {
self.trait_def(trait_def_id).has_auto_impl
}

/// Returns `true` if this is a trait alias.
pub fn trait_is_alias(self, trait_def_id: DefId) -> bool {
self.def_kind(trait_def_id) == DefKind::TraitAlias
}

pub fn trait_is_coinductive(self, trait_def_id: DefId) -> bool {
self.trait_is_auto(trait_def_id) || self.lang_items().sized_trait() == Some(trait_def_id)
}
Expand Down
103 changes: 86 additions & 17 deletions compiler/rustc_trait_selection/src/solve/assembly.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! Code shared by trait and projection goals for candidate assembly.

use super::infcx_ext::InferCtxtExt;
use super::{CanonicalResponse, Certainty, EvalCtxt, Goal};
use super::{CanonicalResponse, EvalCtxt, Goal, QueryResult};
use rustc_hir::def_id::DefId;
use rustc_infer::traits::query::NoSolution;
use rustc_infer::traits::util::elaborate_predicates;
use rustc_middle::ty::TypeFoldable;
use rustc_middle::ty::{self, Ty, TyCtxt};
use std::fmt::Debug;
Expand Down Expand Up @@ -89,19 +90,35 @@ pub(super) trait GoalKind<'tcx>: TypeFoldable<'tcx> + Copy {
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
impl_def_id: DefId,
) -> Result<Certainty, NoSolution>;
) -> QueryResult<'tcx>;

fn consider_assumption(
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
assumption: ty::Predicate<'tcx>,
) -> QueryResult<'tcx>;

fn consider_auto_trait_candidate(
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx>;

fn consider_trait_alias_candidate(
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx>;

fn consider_builtin_sized_candidate(
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> Result<Certainty, NoSolution>;
) -> QueryResult<'tcx>;

fn consider_assumption(
fn consider_builtin_copy_clone_candidate(
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
assumption: ty::Predicate<'tcx>,
) -> Result<Certainty, NoSolution>;
) -> QueryResult<'tcx>;
}

impl<'tcx> EvalCtxt<'_, 'tcx> {
pub(super) fn assemble_and_evaluate_candidates<G: GoalKind<'tcx>>(
&mut self,
Expand All @@ -119,6 +136,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {

self.assemble_alias_bound_candidates(goal, &mut candidates);

self.assemble_object_bound_candidates(goal, &mut candidates);

candidates
}

Expand Down Expand Up @@ -180,9 +199,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
tcx.for_each_relevant_impl(
goal.predicate.trait_def_id(tcx),
goal.predicate.self_ty(),
|impl_def_id| match G::consider_impl_candidate(self, goal, impl_def_id)
.and_then(|certainty| self.make_canonical_response(certainty))
{
|impl_def_id| match G::consider_impl_candidate(self, goal, impl_def_id) {
Ok(result) => candidates
.push(Candidate { source: CandidateSource::Impl(impl_def_id), result }),
Err(NoSolution) => (),
Expand All @@ -197,13 +214,21 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
) {
let lang_items = self.tcx().lang_items();
let trait_def_id = goal.predicate.trait_def_id(self.tcx());
let result = if lang_items.sized_trait() == Some(trait_def_id) {
let result = if self.tcx().trait_is_auto(trait_def_id) {
G::consider_auto_trait_candidate(self, goal)
} else if self.tcx().trait_is_alias(trait_def_id) {
G::consider_trait_alias_candidate(self, goal)
} else if lang_items.sized_trait() == Some(trait_def_id) {
G::consider_builtin_sized_candidate(self, goal)
} else if lang_items.copy_trait() == Some(trait_def_id)
|| lang_items.clone_trait() == Some(trait_def_id)
{
G::consider_builtin_copy_clone_candidate(self, goal)
} else {
Err(NoSolution)
};

match result.and_then(|certainty| self.make_canonical_response(certainty)) {
match result {
Ok(result) => {
candidates.push(Candidate { source: CandidateSource::BuiltinImpl, result })
}
Expand All @@ -217,9 +242,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
candidates: &mut Vec<Candidate<'tcx>>,
) {
for (i, assumption) in goal.param_env.caller_bounds().iter().enumerate() {
match G::consider_assumption(self, goal, assumption)
.and_then(|certainty| self.make_canonical_response(certainty))
{
match G::consider_assumption(self, goal, assumption) {
Ok(result) => {
candidates.push(Candidate { source: CandidateSource::ParamEnv(i), result })
}
Expand Down Expand Up @@ -268,14 +291,60 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
.subst_iter_copied(self.tcx(), alias_ty.substs)
.enumerate()
{
match G::consider_assumption(self, goal, assumption)
.and_then(|certainty| self.make_canonical_response(certainty))
{
match G::consider_assumption(self, goal, assumption) {
Ok(result) => {
candidates.push(Candidate { source: CandidateSource::AliasBound(i), result })
}
Err(NoSolution) => (),
}
}
}

fn assemble_object_bound_candidates<G: GoalKind<'tcx>>(
&mut self,
goal: Goal<'tcx, G>,
candidates: &mut Vec<Candidate<'tcx>>,
) {
let self_ty = goal.predicate.self_ty();
let bounds = match *self_ty.kind() {
ty::Bool
| ty::Char
| ty::Int(_)
| ty::Uint(_)
| ty::Float(_)
| ty::Adt(_, _)
| ty::Foreign(_)
| ty::Str
| ty::Array(_, _)
| ty::Slice(_)
| ty::RawPtr(_)
| ty::Ref(_, _, _)
| ty::FnDef(_, _)
| ty::FnPtr(_)
| ty::Alias(..)
| ty::Closure(..)
| ty::Generator(..)
| ty::GeneratorWitness(_)
| ty::Never
| ty::Tuple(_)
| ty::Param(_)
| ty::Placeholder(..)
| ty::Infer(_)
| ty::Error(_) => return,
ty::Bound(..) => bug!("unexpected bound type: {goal:?}"),
ty::Dynamic(bounds, ..) => bounds,
};

let tcx = self.tcx();
for assumption in
elaborate_predicates(tcx, bounds.iter().map(|bound| bound.with_self_ty(tcx, self_ty)))
{
match G::consider_assumption(self, goal, assumption.predicate) {
Ok(result) => {
candidates.push(Candidate { source: CandidateSource::BuiltinImpl, result })
}
Err(NoSolution) => (),
}
}
Comment on lines +339 to +348
Copy link
Contributor

@lcnr lcnr Jan 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

got reminded of #57893 again :<

}
}
20 changes: 18 additions & 2 deletions compiler/rustc_trait_selection/src/solve/infcx_ext.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use rustc_infer::infer::at::ToTrace;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_infer::infer::{InferCtxt, InferOk};
use rustc_infer::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
use rustc_infer::traits::query::NoSolution;
use rustc_infer::traits::ObligationCause;
use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
use rustc_middle::ty::{self, Ty};
use rustc_middle::ty::{self, Ty, TypeFoldable};
use rustc_span::DUMMY_SP;

use super::Goal;
Expand All @@ -25,6 +25,11 @@ pub(super) trait InferCtxtExt<'tcx> {
lhs: T,
rhs: T,
) -> Result<Vec<Goal<'tcx, ty::Predicate<'tcx>>>, NoSolution>;

fn instantiate_bound_vars_with_infer<T: TypeFoldable<'tcx> + Copy>(
&self,
value: ty::Binder<'tcx, T>,
) -> T;
}

impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
Expand Down Expand Up @@ -59,4 +64,15 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> {
NoSolution
})
}

fn instantiate_bound_vars_with_infer<T: TypeFoldable<'tcx> + Copy>(
&self,
value: ty::Binder<'tcx, T>,
) -> T {
self.replace_bound_vars_with_fresh_vars(
DUMMY_SP,
LateBoundRegionConversionTime::HigherRankedType,
value,
)
}
}
7 changes: 7 additions & 0 deletions compiler/rustc_trait_selection/src/solve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,13 @@ impl<'tcx> EvalCtxt<'_, 'tcx> {
}
})
}

fn evaluate_all_and_make_canonical_response(
&mut self,
goals: Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
) -> QueryResult<'tcx> {
self.evaluate_all(goals).and_then(|certainty| self.make_canonical_response(certainty))
}
}

#[instrument(level = "debug", skip(infcx), ret)]
Expand Down
69 changes: 56 additions & 13 deletions compiler/rustc_trait_selection/src/solve/project_goals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
impl_def_id: DefId,
) -> Result<Certainty, NoSolution> {
) -> QueryResult<'tcx> {
let tcx = ecx.tcx();

let goal_trait_ref = goal.predicate.projection_ty.trait_ref(tcx);
Expand Down Expand Up @@ -229,7 +229,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
impl_def_id
)? else {
let certainty = Certainty::Maybe(MaybeCause::Ambiguity);
return Ok(trait_ref_certainty.unify_and(certainty));
return ecx.make_canonical_response(trait_ref_certainty.unify_and(certainty));
};

if !assoc_def.item.defaultness(tcx).has_value() {
Expand Down Expand Up @@ -286,27 +286,70 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
let rhs_certainty =
ecx.evaluate_all(nested_goals).expect("failed to unify with unconstrained term");

Ok(trait_ref_certainty.unify_and(rhs_certainty))
ecx.make_canonical_response(trait_ref_certainty.unify_and(rhs_certainty))
})
}

fn consider_assumption(
ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
assumption: ty::Predicate<'tcx>,
) -> QueryResult<'tcx> {
if let Some(poly_projection_pred) = assumption.to_opt_poly_projection_pred() {
ecx.infcx.probe(|_| {
let assumption_projection_pred =
ecx.infcx.instantiate_bound_vars_with_infer(poly_projection_pred);
let nested_goals = ecx.infcx.eq(
goal.param_env,
goal.predicate.projection_ty,
assumption_projection_pred.projection_ty,
)?;
let subst_certainty = ecx.evaluate_all(nested_goals)?;

// The term of our goal should be fully unconstrained, so this should never fail.
//
// It can however be ambiguous when the resolved type is a projection.
let nested_goals = ecx
.infcx
.eq(goal.param_env, goal.predicate.term, assumption_projection_pred.term)
.expect("failed to unify with unconstrained term");
let rhs_certainty = ecx
.evaluate_all(nested_goals)
.expect("failed to unify with unconstrained term");

ecx.make_canonical_response(subst_certainty.unify_and(rhs_certainty))
})
} else {
Err(NoSolution)
}
}

fn consider_auto_trait_candidate(
_ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx> {
bug!("auto traits do not have associated types: {:?}", goal);
}

fn consider_trait_alias_candidate(
_ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx> {
bug!("trait aliases do not have associated types: {:?}", goal);
}

fn consider_builtin_sized_candidate(
_ecx: &mut EvalCtxt<'_, 'tcx>,
goal: Goal<'tcx, Self>,
) -> Result<Certainty, NoSolution> {
) -> QueryResult<'tcx> {
bug!("`Sized` does not have an associated type: {:?}", goal);
}

fn consider_assumption(
fn consider_builtin_copy_clone_candidate(
_ecx: &mut EvalCtxt<'_, 'tcx>,
_goal: Goal<'tcx, Self>,
assumption: ty::Predicate<'tcx>,
) -> Result<Certainty, NoSolution> {
if let Some(_poly_projection_pred) = assumption.to_opt_poly_projection_pred() {
unimplemented!()
} else {
Err(NoSolution)
}
goal: Goal<'tcx, Self>,
) -> QueryResult<'tcx> {
bug!("`Copy`/`Clone` does not have an associated type: {:?}", goal);
}
}

Expand Down
Loading