]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/solve/project_goals.rs
Auto merge of #107142 - cuviper:relnotes-1.67, r=Mark-Simulacrum
[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, Candidate, CandidateSource};
4 use super::infcx_ext::InferCtxtExt;
5 use super::trait_goals::structural_traits;
6 use super::{Certainty, EvalCtxt, Goal, QueryResult};
7 use rustc_errors::ErrorGuaranteed;
8 use rustc_hir::def::DefKind;
9 use rustc_hir::def_id::DefId;
10 use rustc_infer::infer::InferCtxt;
11 use rustc_infer::traits::query::NoSolution;
12 use rustc_infer::traits::specialization_graph::LeafDef;
13 use rustc_infer::traits::Reveal;
14 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
15 use rustc_middle::ty::{self, Ty, TyCtxt};
16 use rustc_middle::ty::{ProjectionPredicate, TypeSuperVisitable, TypeVisitor};
17 use rustc_middle::ty::{ToPredicate, TypeVisitable};
18 use rustc_span::DUMMY_SP;
19 use std::iter;
20 use std::ops::ControlFlow;
21
22 impl<'tcx> EvalCtxt<'_, 'tcx> {
23     pub(super) fn compute_projection_goal(
24         &mut self,
25         goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
26     ) -> QueryResult<'tcx> {
27         // To only compute normalization once for each projection we only
28         // normalize if the expected term is an unconstrained inference variable.
29         //
30         // E.g. for `<T as Trait>::Assoc = u32` we recursively compute the goal
31         // `exists<U> <T as Trait>::Assoc = U` and then take the resulting type for
32         // `U` and equate it with `u32`. This means that we don't need a separate
33         // projection cache in the solver.
34         if self.term_is_fully_unconstrained(goal) {
35             let candidates = self.assemble_and_evaluate_candidates(goal);
36             self.merge_project_candidates(candidates)
37         } else {
38             let predicate = goal.predicate;
39             let unconstrained_rhs = match predicate.term.unpack() {
40                 ty::TermKind::Ty(_) => self.infcx.next_ty_infer().into(),
41                 ty::TermKind::Const(ct) => self.infcx.next_const_infer(ct.ty()).into(),
42             };
43             let unconstrained_predicate = ty::Clause::Projection(ProjectionPredicate {
44                 projection_ty: goal.predicate.projection_ty,
45                 term: unconstrained_rhs,
46             });
47             let (_has_changed, normalize_certainty) =
48                 self.evaluate_goal(goal.with(self.tcx(), unconstrained_predicate))?;
49
50             let nested_eq_goals =
51                 self.infcx.eq(goal.param_env, unconstrained_rhs, predicate.term)?;
52             let eval_certainty = self.evaluate_all(nested_eq_goals)?;
53             self.make_canonical_response(normalize_certainty.unify_and(eval_certainty))
54         }
55     }
56
57     /// Is the projection predicate is of the form `exists<T> <Ty as Trait>::Assoc = T`.
58     ///
59     /// This is the case if the `term` is an inference variable in the innermost universe
60     /// and does not occur in any other part of the predicate.
61     fn term_is_fully_unconstrained(&self, goal: Goal<'tcx, ProjectionPredicate<'tcx>>) -> bool {
62         let infcx = self.infcx;
63         let term_is_infer = match goal.predicate.term.unpack() {
64             ty::TermKind::Ty(ty) => {
65                 if let &ty::Infer(ty::TyVar(vid)) = ty.kind() {
66                     match infcx.probe_ty_var(vid) {
67                         Ok(value) => bug!("resolved var in query: {goal:?} {value:?}"),
68                         Err(universe) => universe == infcx.universe(),
69                     }
70                 } else {
71                     false
72                 }
73             }
74             ty::TermKind::Const(ct) => {
75                 if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
76                     match self.infcx.probe_const_var(vid) {
77                         Ok(value) => bug!("resolved var in query: {goal:?} {value:?}"),
78                         Err(universe) => universe == infcx.universe(),
79                     }
80                 } else {
81                     false
82                 }
83             }
84         };
85
86         // Guard against `<T as Trait<?0>>::Assoc = ?0>`.
87         struct ContainsTerm<'tcx> {
88             term: ty::Term<'tcx>,
89         }
90         impl<'tcx> TypeVisitor<'tcx> for ContainsTerm<'tcx> {
91             type BreakTy = ();
92             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
93                 if t.needs_infer() {
94                     if ty::Term::from(t) == self.term {
95                         ControlFlow::BREAK
96                     } else {
97                         t.super_visit_with(self)
98                     }
99                 } else {
100                     ControlFlow::CONTINUE
101                 }
102             }
103
104             fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
105                 if c.needs_infer() {
106                     if ty::Term::from(c) == self.term {
107                         ControlFlow::BREAK
108                     } else {
109                         c.super_visit_with(self)
110                     }
111                 } else {
112                     ControlFlow::CONTINUE
113                 }
114             }
115         }
116
117         let mut visitor = ContainsTerm { term: goal.predicate.term };
118
119         term_is_infer
120             && goal.predicate.projection_ty.visit_with(&mut visitor).is_continue()
121             && goal.param_env.visit_with(&mut visitor).is_continue()
122     }
123
124     fn merge_project_candidates(
125         &mut self,
126         mut candidates: Vec<Candidate<'tcx>>,
127     ) -> QueryResult<'tcx> {
128         match candidates.len() {
129             0 => return Err(NoSolution),
130             1 => return Ok(candidates.pop().unwrap().result),
131             _ => {}
132         }
133
134         if candidates.len() > 1 {
135             let mut i = 0;
136             'outer: while i < candidates.len() {
137                 for j in (0..candidates.len()).filter(|&j| i != j) {
138                     if self.project_candidate_should_be_dropped_in_favor_of(
139                         &candidates[i],
140                         &candidates[j],
141                     ) {
142                         debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
143                         candidates.swap_remove(i);
144                         continue 'outer;
145                     }
146                 }
147
148                 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
149                 // If there are *STILL* multiple candidates, give up
150                 // and report ambiguity.
151                 i += 1;
152                 if i > 1 {
153                     debug!("multiple matches, ambig");
154                     // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
155                     unimplemented!();
156                 }
157             }
158         }
159
160         Ok(candidates.pop().unwrap().result)
161     }
162
163     fn project_candidate_should_be_dropped_in_favor_of(
164         &self,
165         candidate: &Candidate<'tcx>,
166         other: &Candidate<'tcx>,
167     ) -> bool {
168         // FIXME: implement this
169         match (candidate.source, other.source) {
170             (CandidateSource::Impl(_), _)
171             | (CandidateSource::ParamEnv(_), _)
172             | (CandidateSource::BuiltinImpl, _)
173             | (CandidateSource::AliasBound(_), _) => unimplemented!(),
174         }
175     }
176 }
177
178 impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
179     fn self_ty(self) -> Ty<'tcx> {
180         self.self_ty()
181     }
182
183     fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
184         self.with_self_ty(tcx, self_ty)
185     }
186
187     fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
188         self.trait_def_id(tcx)
189     }
190
191     fn consider_impl_candidate(
192         ecx: &mut EvalCtxt<'_, 'tcx>,
193         goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
194         impl_def_id: DefId,
195     ) -> QueryResult<'tcx> {
196         let tcx = ecx.tcx();
197
198         let goal_trait_ref = goal.predicate.projection_ty.trait_ref(tcx);
199         let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
200         let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
201         if iter::zip(goal_trait_ref.substs, impl_trait_ref.skip_binder().substs)
202             .any(|(goal, imp)| !drcx.generic_args_may_unify(goal, imp))
203         {
204             return Err(NoSolution);
205         }
206
207         ecx.infcx.probe(|_| {
208             let impl_substs = ecx.infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
209             let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
210
211             let mut nested_goals = ecx.infcx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?;
212             let where_clause_bounds = tcx
213                 .predicates_of(impl_def_id)
214                 .instantiate(tcx, impl_substs)
215                 .predicates
216                 .into_iter()
217                 .map(|pred| goal.with(tcx, pred));
218
219             nested_goals.extend(where_clause_bounds);
220             let trait_ref_certainty = ecx.evaluate_all(nested_goals)?;
221
222             // In case the associated item is hidden due to specialization, we have to
223             // return ambiguity this would otherwise be incomplete, resulting in
224             // unsoundness during coherence (#105782).
225             let Some(assoc_def) = fetch_eligible_assoc_item_def(
226                 ecx.infcx,
227                 goal.param_env,
228                 goal_trait_ref,
229                 goal.predicate.def_id(),
230                 impl_def_id
231             )? else {
232                 return ecx.make_canonical_response(trait_ref_certainty.unify_and(Certainty::AMBIGUOUS));
233             };
234
235             if !assoc_def.item.defaultness(tcx).has_value() {
236                 tcx.sess.delay_span_bug(
237                     tcx.def_span(assoc_def.item.def_id),
238                     "missing value for assoc item in impl",
239                 );
240             }
241
242             // Getting the right substitutions here is complex, e.g. given:
243             // - a goal `<Vec<u32> as Trait<i32>>::Assoc<u64>`
244             // - the applicable impl `impl<T> Trait<i32> for Vec<T>`
245             // - and the impl which defines `Assoc` being `impl<T, U> Trait<U> for Vec<T>`
246             //
247             // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]`
248             // to `[u32, u64]`.
249             //
250             // And then map these substs to the substs of the defining impl of `Assoc`, going
251             // from `[u32, u64]` to `[u32, i32, u64]`.
252             let impl_substs_with_gat = goal.predicate.projection_ty.substs.rebase_onto(
253                 tcx,
254                 goal_trait_ref.def_id,
255                 impl_substs,
256             );
257             let substs = translate_substs(
258                 ecx.infcx,
259                 goal.param_env,
260                 impl_def_id,
261                 impl_substs_with_gat,
262                 assoc_def.defining_node,
263             );
264
265             // Finally we construct the actual value of the associated type.
266             let is_const = matches!(tcx.def_kind(assoc_def.item.def_id), DefKind::AssocConst);
267             let ty = tcx.bound_type_of(assoc_def.item.def_id);
268             let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
269                 let identity_substs =
270                     ty::InternalSubsts::identity_for_item(tcx, assoc_def.item.def_id);
271                 let did = ty::WithOptConstParam::unknown(assoc_def.item.def_id);
272                 let kind =
273                     ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
274                 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
275             } else {
276                 ty.map_bound(|ty| ty.into())
277             };
278
279             // The term of our goal should be fully unconstrained, so this should never fail.
280             //
281             // It can however be ambiguous when the resolved type is a projection.
282             let nested_goals = ecx
283                 .infcx
284                 .eq(goal.param_env, goal.predicate.term, term.subst(tcx, substs))
285                 .expect("failed to unify with unconstrained term");
286             let rhs_certainty =
287                 ecx.evaluate_all(nested_goals).expect("failed to unify with unconstrained term");
288
289             ecx.make_canonical_response(trait_ref_certainty.unify_and(rhs_certainty))
290         })
291     }
292
293     fn consider_assumption(
294         ecx: &mut EvalCtxt<'_, 'tcx>,
295         goal: Goal<'tcx, Self>,
296         assumption: ty::Predicate<'tcx>,
297     ) -> QueryResult<'tcx> {
298         if let Some(poly_projection_pred) = assumption.to_opt_poly_projection_pred() {
299             ecx.infcx.probe(|_| {
300                 let assumption_projection_pred =
301                     ecx.infcx.instantiate_bound_vars_with_infer(poly_projection_pred);
302                 let nested_goals = ecx.infcx.eq(
303                     goal.param_env,
304                     goal.predicate.projection_ty,
305                     assumption_projection_pred.projection_ty,
306                 )?;
307                 let subst_certainty = ecx.evaluate_all(nested_goals)?;
308
309                 // The term of our goal should be fully unconstrained, so this should never fail.
310                 //
311                 // It can however be ambiguous when the resolved type is a projection.
312                 let nested_goals = ecx
313                     .infcx
314                     .eq(goal.param_env, goal.predicate.term, assumption_projection_pred.term)
315                     .expect("failed to unify with unconstrained term");
316                 let rhs_certainty = ecx
317                     .evaluate_all(nested_goals)
318                     .expect("failed to unify with unconstrained term");
319
320                 ecx.make_canonical_response(subst_certainty.unify_and(rhs_certainty))
321             })
322         } else {
323             Err(NoSolution)
324         }
325     }
326
327     fn consider_auto_trait_candidate(
328         _ecx: &mut EvalCtxt<'_, 'tcx>,
329         goal: Goal<'tcx, Self>,
330     ) -> QueryResult<'tcx> {
331         bug!("auto traits do not have associated types: {:?}", goal);
332     }
333
334     fn consider_trait_alias_candidate(
335         _ecx: &mut EvalCtxt<'_, 'tcx>,
336         goal: Goal<'tcx, Self>,
337     ) -> QueryResult<'tcx> {
338         bug!("trait aliases do not have associated types: {:?}", goal);
339     }
340
341     fn consider_builtin_sized_candidate(
342         _ecx: &mut EvalCtxt<'_, 'tcx>,
343         goal: Goal<'tcx, Self>,
344     ) -> QueryResult<'tcx> {
345         bug!("`Sized` does not have an associated type: {:?}", goal);
346     }
347
348     fn consider_builtin_copy_clone_candidate(
349         _ecx: &mut EvalCtxt<'_, 'tcx>,
350         goal: Goal<'tcx, Self>,
351     ) -> QueryResult<'tcx> {
352         bug!("`Copy`/`Clone` does not have an associated type: {:?}", goal);
353     }
354
355     fn consider_builtin_pointer_sized_candidate(
356         _ecx: &mut EvalCtxt<'_, 'tcx>,
357         goal: Goal<'tcx, Self>,
358     ) -> QueryResult<'tcx> {
359         bug!("`PointerSized` does not have an associated type: {:?}", goal);
360     }
361
362     fn consider_builtin_fn_trait_candidates(
363         ecx: &mut EvalCtxt<'_, 'tcx>,
364         goal: Goal<'tcx, Self>,
365         goal_kind: ty::ClosureKind,
366     ) -> QueryResult<'tcx> {
367         if let Some(tupled_inputs_and_output) =
368             structural_traits::extract_tupled_inputs_and_output_from_callable(
369                 ecx.tcx(),
370                 goal.predicate.self_ty(),
371                 goal_kind,
372             )?
373         {
374             let pred = tupled_inputs_and_output
375                 .map_bound(|(inputs, output)| ty::ProjectionPredicate {
376                     projection_ty: ecx
377                         .tcx()
378                         .mk_alias_ty(goal.predicate.def_id(), [goal.predicate.self_ty(), inputs]),
379                     term: output.into(),
380                 })
381                 .to_predicate(ecx.tcx());
382             Self::consider_assumption(ecx, goal, pred)
383         } else {
384             ecx.make_canonical_response(Certainty::AMBIGUOUS)
385         }
386     }
387
388     fn consider_builtin_tuple_candidate(
389         _ecx: &mut EvalCtxt<'_, 'tcx>,
390         goal: Goal<'tcx, Self>,
391     ) -> QueryResult<'tcx> {
392         bug!("`Tuple` does not have an associated type: {:?}", goal);
393     }
394 }
395
396 /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code.
397 ///
398 /// FIXME: We should merge these 3 implementations as it's likely that they otherwise
399 /// diverge.
400 #[instrument(level = "debug", skip(infcx, param_env), ret)]
401 fn fetch_eligible_assoc_item_def<'tcx>(
402     infcx: &InferCtxt<'tcx>,
403     param_env: ty::ParamEnv<'tcx>,
404     goal_trait_ref: ty::TraitRef<'tcx>,
405     trait_assoc_def_id: DefId,
406     impl_def_id: DefId,
407 ) -> Result<Option<LeafDef>, NoSolution> {
408     let node_item = specialization_graph::assoc_def(infcx.tcx, impl_def_id, trait_assoc_def_id)
409         .map_err(|ErrorGuaranteed { .. }| NoSolution)?;
410
411     let eligible = if node_item.is_final() {
412         // Non-specializable items are always projectable.
413         true
414     } else {
415         // Only reveal a specializable default if we're past type-checking
416         // and the obligation is monomorphic, otherwise passes such as
417         // transmute checking and polymorphic MIR optimizations could
418         // get a result which isn't correct for all monomorphizations.
419         if param_env.reveal() == Reveal::All {
420             let poly_trait_ref = infcx.resolve_vars_if_possible(goal_trait_ref);
421             !poly_trait_ref.still_further_specializable()
422         } else {
423             debug!(?node_item.item.def_id, "not eligible due to default");
424             false
425         }
426     };
427
428     if eligible { Ok(Some(node_item)) } else { Ok(None) }
429 }