]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/solve/project_goals.rs
47a8f59ceb77f2fb0ebb2b76218c2e78f580c78a
[rust.git] / compiler / rustc_trait_selection / src / solve / project_goals.rs
1 use crate::traits::{specialization_graph, translate_substs};
2
3 use super::infcx_ext::InferCtxtExt;
4 use super::{
5     fixme_instantiate_canonical_query_response, CanonicalGoal, CanonicalResponse, Certainty,
6     EvalCtxt, Goal, QueryResult,
7 };
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};
16 use rustc_middle::ty;
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;
21 use std::iter;
22
23 // FIXME: Deduplicate the candidate code between projection and trait goal.
24
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>,
30 }
31
32 #[allow(dead_code)] // FIXME: implement and use all variants.
33 #[derive(Debug, Clone, Copy)]
34 enum CandidateSource {
35     Impl(DefId),
36     ParamEnv(usize),
37     Builtin,
38 }
39
40 impl<'tcx> EvalCtxt<'tcx> {
41     pub(super) fn compute_projection_goal(
42         &mut self,
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)
47     }
48
49     fn assemble_and_evaluate_project_candidates(
50         &mut self,
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() };
56
57         acx.assemble_candidates_after_normalizing_self_ty(goal);
58         acx.assemble_impl_candidates(goal);
59         acx.candidates
60     }
61
62     fn merge_project_candidates(
63         &mut self,
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),
69             _ => {}
70         }
71
72         if candidates.len() > 1 {
73             let mut i = 0;
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(
77                         &candidates[i],
78                         &candidates[j],
79                     ) {
80                         debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
81                         candidates.swap_remove(i);
82                         continue 'outer;
83                     }
84                 }
85
86                 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
87                 // If there are *STILL* multiple candidates, give up
88                 // and report ambiguity.
89                 i += 1;
90                 if i > 1 {
91                     debug!("multiple matches, ambig");
92                     // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
93                     unimplemented!();
94                 }
95             }
96         }
97
98         Ok(candidates.pop().unwrap().result)
99     }
100
101     fn project_candidate_should_be_dropped_in_favor_of(
102         &self,
103         candidate: &Candidate<'tcx>,
104         other: &Candidate<'tcx>,
105     ) -> bool {
106         // FIXME: implement this
107         match (candidate.source, other.source) {
108             (CandidateSource::Impl(_), _)
109             | (CandidateSource::ParamEnv(_), _)
110             | (CandidateSource::Builtin, _) => unimplemented!(),
111         }
112     }
113 }
114
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>>,
121 }
122
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"),
128         }
129     }
130
131     fn assemble_candidates_after_normalizing_self_ty(
132         &mut self,
133         goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
134     ) {
135         let tcx = self.cx.tcx;
136         let &ty::Alias(ty::Projection, projection_ty) = goal.predicate.projection_ty.self_ty().kind() else {
137             return
138         };
139         self.infcx.probe(|_| {
140             let normalized_ty = self.infcx.next_ty_infer();
141             let normalizes_to_goal = goal.with(
142                 tcx,
143                 ty::Binder::dummy(ty::ProjectionPredicate {
144                     projection_ty,
145                     term: normalized_ty.into(),
146                 }),
147             );
148             let normalization_certainty =
149                 match self.cx.evaluate_goal(&self.infcx, normalizes_to_goal) {
150                     Ok((_, certainty)) => certainty,
151                     Err(NoSolution) => return,
152                 };
153
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(
165                         self.infcx,
166                         &orig_values,
167                         result,
168                     );
169                     self.try_insert_candidate(
170                         source,
171                         normalization_certainty.unify_and(candidate_certainty),
172                     )
173                 })
174             }
175         })
176     }
177
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),
183         );
184     }
185
186     fn consider_impl_candidate(
187         &mut self,
188         goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
189         impl_def_id: DefId,
190     ) {
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))
197         {
198             return;
199         }
200
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);
204
205             let Ok(InferOk { obligations, .. }) = self
206                 .infcx
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:?}"))
211             else {
212                 return
213             };
214
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 };
217
218             let Some(assoc_def) = self.fetch_eligible_assoc_item_def(
219                 goal.param_env,
220                 goal_trait_ref,
221                 goal.predicate.def_id(),
222                 impl_def_id
223             ) else {
224                 return
225             };
226
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",
231                 );
232             }
233
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>`
238             //
239             // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]`
240             // to `[u32, u64]`.
241             //
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(
245                 tcx,
246                 goal_trait_ref.def_id,
247                 impl_trait_ref.substs,
248             );
249             let substs = translate_substs(
250                 self.infcx,
251                 goal.param_env,
252                 impl_def_id,
253                 impl_substs_with_gat,
254                 assoc_def.defining_node,
255             );
256
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);
263                 let kind =
264                     ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
265                 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
266             } else {
267                 ty.map_bound(|ty| ty.into())
268             };
269
270             let Ok(InferOk { obligations, .. }) = self
271                 .infcx
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:?}"))
276             else {
277                 return
278             };
279
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 };
282
283             let certainty = trait_ref_certainty.unify_and(rhs_certainty);
284             self.try_insert_candidate(CandidateSource::Impl(impl_def_id), certainty);
285         })
286     }
287
288     /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code.
289     ///
290     /// FIXME: We should merge these 3 implementations as it's likely that they otherwise
291     /// diverge.
292     #[instrument(level = "debug", skip(self, param_env), ret)]
293     fn fetch_eligible_assoc_item_def(
294         &self,
295         param_env: ty::ParamEnv<'tcx>,
296         goal_trait_ref: ty::TraitRef<'tcx>,
297         trait_assoc_def_id: DefId,
298         impl_def_id: DefId,
299     ) -> Option<LeafDef> {
300         let node_item =
301             specialization_graph::assoc_def(self.cx.tcx, impl_def_id, trait_assoc_def_id)
302                 .map_err(|ErrorGuaranteed { .. }| ())
303                 .ok()?;
304
305         let eligible = if node_item.is_final() {
306             // Non-specializable items are always projectable.
307             true
308         } else {
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()
316             } else {
317                 debug!(?node_item.item.def_id, "not eligible due to default");
318                 false
319             }
320         };
321
322         if eligible { Some(node_item) } else { None }
323     }
324 }