]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/solve/project_goals.rs
1120dfb8098628ca751ec77984c71929f1a2d94f
[rust.git] / compiler / rustc_trait_selection / src / solve / project_goals.rs
1 use crate::traits::{specialization_graph, translate_substs};
2
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;
17 use std::iter;
18
19 #[allow(dead_code)] // FIXME: implement and use all variants.
20 #[derive(Debug, Clone, Copy)]
21 pub(super) enum CandidateSource {
22     Impl(DefId),
23     ParamEnv(usize),
24     Builtin,
25 }
26
27 type Candidate<'tcx> = assembly::Candidate<'tcx, ProjectionPredicate<'tcx>>;
28
29 impl<'tcx> EvalCtxt<'_, 'tcx> {
30     pub(super) fn compute_projection_goal(
31         &mut self,
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)
36     }
37
38     fn merge_project_candidates(
39         &mut self,
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),
45             _ => {}
46         }
47
48         if candidates.len() > 1 {
49             let mut i = 0;
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(
53                         &candidates[i],
54                         &candidates[j],
55                     ) {
56                         debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
57                         candidates.swap_remove(i);
58                         continue 'outer;
59                     }
60                 }
61
62                 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
63                 // If there are *STILL* multiple candidates, give up
64                 // and report ambiguity.
65                 i += 1;
66                 if i > 1 {
67                     debug!("multiple matches, ambig");
68                     // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
69                     unimplemented!();
70                 }
71             }
72         }
73
74         Ok(candidates.pop().unwrap().result)
75     }
76
77     fn project_candidate_should_be_dropped_in_favor_of(
78         &self,
79         candidate: &Candidate<'tcx>,
80         other: &Candidate<'tcx>,
81     ) -> bool {
82         // FIXME: implement this
83         match (candidate.source, other.source) {
84             (CandidateSource::Impl(_), _)
85             | (CandidateSource::ParamEnv(_), _)
86             | (CandidateSource::Builtin, _) => unimplemented!(),
87         }
88     }
89 }
90
91 impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
92     type CandidateSource = CandidateSource;
93
94     fn self_ty(self) -> Ty<'tcx> {
95         self.self_ty()
96     }
97
98     fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
99         self.with_self_ty(tcx, self_ty)
100     }
101
102     fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
103         self.trait_def_id(tcx)
104     }
105
106     fn consider_impl_candidate(
107         acx: &mut AssemblyCtxt<'_, '_, 'tcx, ProjectionPredicate<'tcx>>,
108         goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
109         impl_def_id: DefId,
110     ) {
111         let tcx = acx.cx.tcx();
112         let infcx = acx.cx.infcx;
113
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))
119         {
120             return;
121         }
122
123         infcx.probe(|_| {
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);
126
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:?}"))
132             else {
133                 return
134             };
135             let where_clause_bounds = tcx
136                 .predicates_of(impl_def_id)
137                 .instantiate(tcx, impl_substs)
138                 .predicates
139                 .into_iter()
140                 .map(|pred| goal.with(tcx, pred));
141
142             let nested_goals =
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 };
145
146             let Some(assoc_def) = fetch_eligible_assoc_item_def(
147                 infcx,
148                 goal.param_env,
149                 goal_trait_ref,
150                 goal.predicate.def_id(),
151                 impl_def_id
152             ) else {
153                 return
154             };
155
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",
160                 );
161             }
162
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>`
167             //
168             // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]`
169             // to `[u32, u64]`.
170             //
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(
174                 tcx,
175                 goal_trait_ref.def_id,
176                 impl_substs,
177             );
178             let substs = translate_substs(
179                 infcx,
180                 goal.param_env,
181                 impl_def_id,
182                 impl_substs_with_gat,
183                 assoc_def.defining_node,
184             );
185
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);
193                 let kind =
194                     ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
195                 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
196             } else {
197                 ty.map_bound(|ty| ty.into())
198             };
199
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:?}"))
205             else {
206                 return
207             };
208
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 };
211
212             let certainty = trait_ref_certainty.unify_and(rhs_certainty);
213             acx.try_insert_candidate(CandidateSource::Impl(impl_def_id), certainty);
214         })
215     }
216 }
217
218 /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code.
219 ///
220 /// FIXME: We should merge these 3 implementations as it's likely that they otherwise
221 /// diverge.
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,
228     impl_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 { .. }| ())
232         .ok()?;
233
234     let eligible = if node_item.is_final() {
235         // Non-specializable items are always projectable.
236         true
237     } else {
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()
245         } else {
246             debug!(?node_item.item.def_id, "not eligible due to default");
247             false
248         }
249     };
250
251     if eligible { Some(node_item) } else { None }
252 }