1 use crate::traits::{specialization_graph, translate_substs};
3 use super::assembly::{self, AssemblyCtxt};
4 use super::{EvalCtxt, Goal, QueryResult};
5 use rustc_errors::ErrorGuaranteed;
6 use rustc_hir::def::DefKind;
7 use rustc_hir::def_id::DefId;
8 use rustc_infer::infer::{InferCtxt, InferOk};
9 use rustc_infer::traits::query::NoSolution;
10 use rustc_infer::traits::specialization_graph::LeafDef;
11 use rustc_infer::traits::{ObligationCause, Reveal};
12 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
13 use rustc_middle::ty::ProjectionPredicate;
14 use rustc_middle::ty::TypeVisitable;
15 use rustc_middle::ty::{self, Ty, TyCtxt};
16 use rustc_span::DUMMY_SP;
19 #[allow(dead_code)] // FIXME: implement and use all variants.
20 #[derive(Debug, Clone, Copy)]
21 pub(super) enum CandidateSource {
27 type Candidate<'tcx> = assembly::Candidate<'tcx, ProjectionPredicate<'tcx>>;
29 impl<'tcx> EvalCtxt<'_, 'tcx> {
30 pub(super) fn compute_projection_goal(
32 goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
33 ) -> QueryResult<'tcx> {
34 let candidates = AssemblyCtxt::assemble_and_evaluate_candidates(self, goal);
35 self.merge_project_candidates(candidates)
38 fn merge_project_candidates(
40 mut candidates: Vec<Candidate<'tcx>>,
41 ) -> QueryResult<'tcx> {
42 match candidates.len() {
43 0 => return Err(NoSolution),
44 1 => return Ok(candidates.pop().unwrap().result),
48 if candidates.len() > 1 {
50 'outer: while i < candidates.len() {
51 for j in (0..candidates.len()).filter(|&j| i != j) {
52 if self.project_candidate_should_be_dropped_in_favor_of(
56 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
57 candidates.swap_remove(i);
62 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
63 // If there are *STILL* multiple candidates, give up
64 // and report ambiguity.
67 debug!("multiple matches, ambig");
68 // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
74 Ok(candidates.pop().unwrap().result)
77 fn project_candidate_should_be_dropped_in_favor_of(
79 candidate: &Candidate<'tcx>,
80 other: &Candidate<'tcx>,
82 // FIXME: implement this
83 match (candidate.source, other.source) {
84 (CandidateSource::Impl(_), _)
85 | (CandidateSource::ParamEnv(_), _)
86 | (CandidateSource::Builtin, _) => unimplemented!(),
91 impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
92 type CandidateSource = CandidateSource;
94 fn self_ty(self) -> Ty<'tcx> {
98 fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
99 self.with_self_ty(tcx, self_ty)
102 fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
103 self.trait_def_id(tcx)
106 fn consider_impl_candidate(
107 acx: &mut AssemblyCtxt<'_, '_, 'tcx, ProjectionPredicate<'tcx>>,
108 goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
111 let tcx = acx.cx.tcx();
112 let infcx = acx.cx.infcx;
114 let goal_trait_ref = goal.predicate.projection_ty.trait_ref(tcx);
115 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
116 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
117 if iter::zip(goal_trait_ref.substs, impl_trait_ref.skip_binder().substs)
118 .any(|(goal, imp)| !drcx.generic_args_may_unify(goal, imp))
124 let impl_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
125 let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
127 let Ok(InferOk { obligations, .. }) = infcx
128 .at(&ObligationCause::dummy(), goal.param_env)
129 .define_opaque_types(false)
130 .eq(goal_trait_ref, impl_trait_ref)
131 .map_err(|e| debug!("failed to equate trait refs: {e:?}"))
135 let where_clause_bounds = tcx
136 .predicates_of(impl_def_id)
137 .instantiate(tcx, impl_substs)
140 .map(|pred| goal.with(tcx, pred));
143 obligations.into_iter().map(|o| o.into()).chain(where_clause_bounds).collect();
144 let Ok(trait_ref_certainty) = acx.cx.evaluate_all(nested_goals) else { return };
146 let Some(assoc_def) = fetch_eligible_assoc_item_def(
150 goal.predicate.def_id(),
156 if !assoc_def.item.defaultness(tcx).has_value() {
157 tcx.sess.delay_span_bug(
158 tcx.def_span(assoc_def.item.def_id),
159 "missing value for assoc item in impl",
163 // Getting the right substitutions here is complex, e.g. given:
164 // - a goal `<Vec<u32> as Trait<i32>>::Assoc<u64>`
165 // - the applicable impl `impl<T> Trait<i32> for Vec<T>`
166 // - and the impl which defines `Assoc` being `impl<T, U> Trait<U> for Vec<T>`
168 // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]`
171 // And then map these substs to the substs of the defining impl of `Assoc`, going
172 // from `[u32, u64]` to `[u32, i32, u64]`.
173 let impl_substs_with_gat = goal.predicate.projection_ty.substs.rebase_onto(
175 goal_trait_ref.def_id,
178 let substs = translate_substs(
182 impl_substs_with_gat,
183 assoc_def.defining_node,
186 // Finally we construct the actual value of the associated type.
187 let is_const = matches!(tcx.def_kind(assoc_def.item.def_id), DefKind::AssocConst);
188 let ty = tcx.bound_type_of(assoc_def.item.def_id);
189 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
190 let identity_substs =
191 ty::InternalSubsts::identity_for_item(tcx, assoc_def.item.def_id);
192 let did = ty::WithOptConstParam::unknown(assoc_def.item.def_id);
194 ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
195 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
197 ty.map_bound(|ty| ty.into())
200 let Ok(InferOk { obligations, .. }) = infcx
201 .at(&ObligationCause::dummy(), goal.param_env)
202 .define_opaque_types(false)
203 .eq(goal.predicate.term, term.subst(tcx, substs))
204 .map_err(|e| debug!("failed to equate trait refs: {e:?}"))
209 let nested_goals = obligations.into_iter().map(|o| o.into()).collect();
210 let Ok(rhs_certainty) = acx.cx.evaluate_all(nested_goals) else { return };
212 let certainty = trait_ref_certainty.unify_and(rhs_certainty);
213 acx.try_insert_candidate(CandidateSource::Impl(impl_def_id), certainty);
218 /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code.
220 /// FIXME: We should merge these 3 implementations as it's likely that they otherwise
222 #[instrument(level = "debug", skip(infcx, param_env), ret)]
223 fn fetch_eligible_assoc_item_def<'tcx>(
224 infcx: &InferCtxt<'tcx>,
225 param_env: ty::ParamEnv<'tcx>,
226 goal_trait_ref: ty::TraitRef<'tcx>,
227 trait_assoc_def_id: DefId,
229 ) -> Option<LeafDef> {
230 let node_item = specialization_graph::assoc_def(infcx.tcx, impl_def_id, trait_assoc_def_id)
231 .map_err(|ErrorGuaranteed { .. }| ())
234 let eligible = if node_item.is_final() {
235 // Non-specializable items are always projectable.
238 // Only reveal a specializable default if we're past type-checking
239 // and the obligation is monomorphic, otherwise passes such as
240 // transmute checking and polymorphic MIR optimizations could
241 // get a result which isn't correct for all monomorphizations.
242 if param_env.reveal() == Reveal::All {
243 let poly_trait_ref = infcx.resolve_vars_if_possible(goal_trait_ref);
244 !poly_trait_ref.still_further_specializable()
246 debug!(?node_item.item.def_id, "not eligible due to default");
251 if eligible { Some(node_item) } else { None }