1 use crate::traits::{specialization_graph, translate_substs};
3 use super::infcx_ext::InferCtxtExt;
5 fixme_instantiate_canonical_query_response, CanonicalGoal, CanonicalResponse, Certainty,
6 EvalCtxt, Goal, QueryResult,
8 use rustc_errors::ErrorGuaranteed;
9 use rustc_hir::def::DefKind;
10 use rustc_hir::def_id::DefId;
11 use rustc_infer::infer::canonical::{CanonicalVarValues, OriginalQueryValues};
12 use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
13 use rustc_infer::traits::query::NoSolution;
14 use rustc_infer::traits::specialization_graph::LeafDef;
15 use rustc_infer::traits::{ObligationCause, Reveal};
17 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
18 use rustc_middle::ty::ProjectionPredicate;
19 use rustc_middle::ty::TypeVisitable;
20 use rustc_span::DUMMY_SP;
23 // FIXME: Deduplicate the candidate code between projection and trait goal.
25 /// Similar to [super::trait_goals::Candidate] but for `Projection` goals.
26 #[derive(Debug, Clone)]
27 struct Candidate<'tcx> {
28 source: CandidateSource,
29 result: CanonicalResponse<'tcx>,
32 #[allow(dead_code)] // FIXME: implement and use all variants.
33 #[derive(Debug, Clone, Copy)]
34 enum CandidateSource {
40 impl<'tcx> EvalCtxt<'tcx> {
41 pub(super) fn compute_projection_goal(
43 goal: CanonicalGoal<'tcx, ProjectionPredicate<'tcx>>,
44 ) -> QueryResult<'tcx> {
45 let candidates = self.assemble_and_evaluate_project_candidates(goal);
46 self.merge_project_candidates(candidates)
49 fn assemble_and_evaluate_project_candidates(
51 goal: CanonicalGoal<'tcx, ProjectionPredicate<'tcx>>,
52 ) -> Vec<Candidate<'tcx>> {
53 let (ref infcx, goal, var_values) =
54 self.tcx.infer_ctxt().build_with_canonical(DUMMY_SP, &goal);
55 let mut acx = AssemblyCtxt { cx: self, infcx, var_values, candidates: Vec::new() };
57 acx.assemble_candidates_after_normalizing_self_ty(goal);
58 acx.assemble_impl_candidates(goal);
62 fn merge_project_candidates(
64 mut candidates: Vec<Candidate<'tcx>>,
65 ) -> QueryResult<'tcx> {
66 match candidates.len() {
67 0 => return Err(NoSolution),
68 1 => return Ok(candidates.pop().unwrap().result),
72 if candidates.len() > 1 {
74 'outer: while i < candidates.len() {
75 for j in (0..candidates.len()).filter(|&j| i != j) {
76 if self.project_candidate_should_be_dropped_in_favor_of(
80 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
81 candidates.swap_remove(i);
86 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
87 // If there are *STILL* multiple candidates, give up
88 // and report ambiguity.
91 debug!("multiple matches, ambig");
92 // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
98 Ok(candidates.pop().unwrap().result)
101 fn project_candidate_should_be_dropped_in_favor_of(
103 candidate: &Candidate<'tcx>,
104 other: &Candidate<'tcx>,
106 // FIXME: implement this
107 match (candidate.source, other.source) {
108 (CandidateSource::Impl(_), _)
109 | (CandidateSource::ParamEnv(_), _)
110 | (CandidateSource::Builtin, _) => unimplemented!(),
115 /// Similar to [super::trait_goals::AssemblyCtxt] but for `Projection` goals.
116 struct AssemblyCtxt<'a, 'tcx> {
117 cx: &'a mut EvalCtxt<'tcx>,
118 infcx: &'a InferCtxt<'tcx>,
119 var_values: CanonicalVarValues<'tcx>,
120 candidates: Vec<Candidate<'tcx>>,
123 impl<'tcx> AssemblyCtxt<'_, 'tcx> {
124 fn try_insert_candidate(&mut self, source: CandidateSource, certainty: Certainty) {
125 match self.infcx.make_canonical_response(self.var_values.clone(), certainty) {
126 Ok(result) => self.candidates.push(Candidate { source, result }),
127 Err(NoSolution) => debug!(?source, ?certainty, "failed leakcheck"),
131 fn assemble_candidates_after_normalizing_self_ty(
133 goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
135 let tcx = self.cx.tcx;
136 let &ty::Alias(ty::Projection, projection_ty) = goal.predicate.projection_ty.self_ty().kind() else {
139 self.infcx.probe(|_| {
140 let normalized_ty = self.infcx.next_ty_infer();
141 let normalizes_to_goal = goal.with(
143 ty::Binder::dummy(ty::ProjectionPredicate {
145 term: normalized_ty.into(),
148 let normalization_certainty =
149 match self.cx.evaluate_goal(&self.infcx, normalizes_to_goal) {
150 Ok((_, certainty)) => certainty,
151 Err(NoSolution) => return,
154 // NOTE: Alternatively we could call `evaluate_goal` here and only have a `Normalized` candidate.
155 // This doesn't work as long as we use `CandidateSource` in both winnowing and to resolve associated items.
156 let goal = goal.with(tcx, goal.predicate.with_self_ty(tcx, normalized_ty));
157 let mut orig_values = OriginalQueryValues::default();
158 let goal = self.infcx.canonicalize_query(goal, &mut orig_values);
159 let normalized_candidates = self.cx.assemble_and_evaluate_project_candidates(goal);
160 // Map each candidate from being canonical wrt the current inference context to being
161 // canonical wrt the caller.
162 for Candidate { source, result } in normalized_candidates {
163 self.infcx.probe(|_| {
164 let candidate_certainty = fixme_instantiate_canonical_query_response(
169 self.try_insert_candidate(
171 normalization_certainty.unify_and(candidate_certainty),
178 fn assemble_impl_candidates(&mut self, goal: Goal<'tcx, ProjectionPredicate<'tcx>>) {
179 self.cx.tcx.for_each_relevant_impl(
180 goal.predicate.trait_def_id(self.cx.tcx),
181 goal.predicate.self_ty(),
182 |impl_def_id| self.consider_impl_candidate(goal, impl_def_id),
186 fn consider_impl_candidate(
188 goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
191 let tcx = self.cx.tcx;
192 let goal_trait_ref = goal.predicate.projection_ty.trait_ref(tcx);
193 let impl_trait_ref = tcx.bound_impl_trait_ref(impl_def_id).unwrap();
194 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
195 if iter::zip(goal_trait_ref.substs, impl_trait_ref.skip_binder().substs)
196 .any(|(goal, imp)| !drcx.generic_args_may_unify(goal, imp))
201 self.infcx.probe(|_| {
202 let impl_substs = self.infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
203 let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
205 let Ok(InferOk { obligations, .. }) = self
207 .at(&ObligationCause::dummy(), goal.param_env)
208 .define_opaque_types(false)
209 .eq(goal_trait_ref, impl_trait_ref)
210 .map_err(|e| debug!("failed to equate trait refs: {e:?}"))
215 let nested_goals = obligations.into_iter().map(|o| o.into()).collect();
216 let Ok(trait_ref_certainty) = self.cx.evaluate_all(self.infcx, nested_goals) else { return };
218 let Some(assoc_def) = self.fetch_eligible_assoc_item_def(
221 goal.predicate.def_id(),
227 if !assoc_def.item.defaultness(tcx).has_value() {
228 tcx.sess.delay_span_bug(
229 tcx.def_span(assoc_def.item.def_id),
230 "missing value for assoc item in impl",
234 // Getting the right substitutions here is complex, e.g. given:
235 // - a goal `<Vec<u32> as Trait<i32>>::Assoc<u64>`
236 // - the applicable impl `impl<T> Trait<i32> for Vec<T>`
237 // - and the impl which defines `Assoc` being `impl<T, U> Trait<U> for Vec<T>`
239 // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]`
242 // And then map these substs to the substs of the defining impl of `Assoc`, going
243 // from `[u32, u64]` to `[u32, i32, u64]`.
244 let impl_substs_with_gat = goal.predicate.projection_ty.substs.rebase_onto(
246 goal_trait_ref.def_id,
247 impl_trait_ref.substs,
249 let substs = translate_substs(
253 impl_substs_with_gat,
254 assoc_def.defining_node,
257 // Finally we construct the actual value of the associated type.
258 let is_const = matches!(tcx.def_kind(assoc_def.item.def_id), DefKind::AssocConst);
259 let ty = tcx.bound_type_of(assoc_def.item.def_id);
260 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
261 let identity_substs = ty::InternalSubsts::identity_for_item(tcx, assoc_def.item.def_id);
262 let did = ty::WithOptConstParam::unknown(assoc_def.item.def_id);
264 ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
265 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
267 ty.map_bound(|ty| ty.into())
270 let Ok(InferOk { obligations, .. }) = self
272 .at(&ObligationCause::dummy(), goal.param_env)
273 .define_opaque_types(false)
274 .eq(goal.predicate.term, term.subst(tcx, substs))
275 .map_err(|e| debug!("failed to equate trait refs: {e:?}"))
280 let nested_goals = obligations.into_iter().map(|o| o.into()).collect();
281 let Ok(rhs_certainty) = self.cx.evaluate_all(self.infcx, nested_goals) else { return };
283 let certainty = trait_ref_certainty.unify_and(rhs_certainty);
284 self.try_insert_candidate(CandidateSource::Impl(impl_def_id), certainty);
288 /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code.
290 /// FIXME: We should merge these 3 implementations as it's likely that they otherwise
292 #[instrument(level = "debug", skip(self, param_env), ret)]
293 fn fetch_eligible_assoc_item_def(
295 param_env: ty::ParamEnv<'tcx>,
296 goal_trait_ref: ty::TraitRef<'tcx>,
297 trait_assoc_def_id: DefId,
299 ) -> Option<LeafDef> {
301 specialization_graph::assoc_def(self.cx.tcx, impl_def_id, trait_assoc_def_id)
302 .map_err(|ErrorGuaranteed { .. }| ())
305 let eligible = if node_item.is_final() {
306 // Non-specializable items are always projectable.
309 // Only reveal a specializable default if we're past type-checking
310 // and the obligation is monomorphic, otherwise passes such as
311 // transmute checking and polymorphic MIR optimizations could
312 // get a result which isn't correct for all monomorphizations.
313 if param_env.reveal() == Reveal::All {
314 let poly_trait_ref = self.infcx.resolve_vars_if_possible(goal_trait_ref);
315 !poly_trait_ref.still_further_specializable()
317 debug!(?node_item.item.def_id, "not eligible due to default");
322 if eligible { Some(node_item) } else { None }