1 use crate::traits::{specialization_graph, translate_substs};
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_hir::LangItem;
11 use rustc_infer::infer::InferCtxt;
12 use rustc_infer::traits::query::NoSolution;
13 use rustc_infer::traits::specialization_graph::LeafDef;
14 use rustc_infer::traits::Reveal;
15 use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
16 use rustc_middle::ty::{self, Ty, TyCtxt};
17 use rustc_middle::ty::{ProjectionPredicate, TypeSuperVisitable, TypeVisitor};
18 use rustc_middle::ty::{ToPredicate, TypeVisitable};
19 use rustc_span::{sym, DUMMY_SP};
21 use std::ops::ControlFlow;
23 impl<'tcx> EvalCtxt<'_, 'tcx> {
24 pub(super) fn compute_projection_goal(
26 goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
27 ) -> QueryResult<'tcx> {
28 // To only compute normalization once for each projection we only
29 // normalize if the expected term is an unconstrained inference variable.
31 // E.g. for `<T as Trait>::Assoc == u32` we recursively compute the goal
32 // `exists<U> <T as Trait>::Assoc == U` and then take the resulting type for
33 // `U` and equate it with `u32`. This means that we don't need a separate
34 // projection cache in the solver.
35 if self.term_is_fully_unconstrained(goal) {
36 let candidates = self.assemble_and_evaluate_candidates(goal);
37 self.merge_project_candidates(candidates)
39 let predicate = goal.predicate;
40 let unconstrained_rhs = match predicate.term.unpack() {
41 ty::TermKind::Ty(_) => self.infcx.next_ty_infer().into(),
42 ty::TermKind::Const(ct) => self.infcx.next_const_infer(ct.ty()).into(),
44 let unconstrained_predicate = ty::Clause::Projection(ProjectionPredicate {
45 projection_ty: goal.predicate.projection_ty,
46 term: unconstrained_rhs,
48 let (_has_changed, normalize_certainty) = self.in_projection_eq_hack(|this| {
49 this.evaluate_goal(goal.with(this.tcx(), unconstrained_predicate))
53 self.infcx.eq(goal.param_env, unconstrained_rhs, predicate.term)?;
54 let eval_certainty = self.evaluate_all(nested_eq_goals)?;
55 self.make_canonical_response(normalize_certainty.unify_and(eval_certainty))
59 /// This sets a flag used by a debug assert in [`EvalCtxt::evaluate_goal`],
60 /// see the comment in that method for more details.
61 fn in_projection_eq_hack<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
62 self.in_projection_eq_hack = true;
64 self.in_projection_eq_hack = false;
68 /// Is the projection predicate is of the form `exists<T> <Ty as Trait>::Assoc = T`.
70 /// This is the case if the `term` is an inference variable in the innermost universe
71 /// and does not occur in any other part of the predicate.
72 fn term_is_fully_unconstrained(&self, goal: Goal<'tcx, ProjectionPredicate<'tcx>>) -> bool {
73 let infcx = self.infcx;
74 let term_is_infer = match goal.predicate.term.unpack() {
75 ty::TermKind::Ty(ty) => {
76 if let &ty::Infer(ty::TyVar(vid)) = ty.kind() {
77 match infcx.probe_ty_var(vid) {
78 Ok(value) => bug!("resolved var in query: {goal:?} {value:?}"),
79 Err(universe) => universe == infcx.universe(),
85 ty::TermKind::Const(ct) => {
86 if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
87 match self.infcx.probe_const_var(vid) {
88 Ok(value) => bug!("resolved var in query: {goal:?} {value:?}"),
89 Err(universe) => universe == infcx.universe(),
97 // Guard against `<T as Trait<?0>>::Assoc = ?0>`.
98 struct ContainsTerm<'tcx> {
101 impl<'tcx> TypeVisitor<'tcx> for ContainsTerm<'tcx> {
103 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
105 if ty::Term::from(t) == self.term {
106 ControlFlow::Break(())
108 t.super_visit_with(self)
111 ControlFlow::Continue(())
115 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
117 if ty::Term::from(c) == self.term {
118 ControlFlow::Break(())
120 c.super_visit_with(self)
123 ControlFlow::Continue(())
128 let mut visitor = ContainsTerm { term: goal.predicate.term };
131 && goal.predicate.projection_ty.visit_with(&mut visitor).is_continue()
132 && goal.param_env.visit_with(&mut visitor).is_continue()
135 /// After normalizing the projection to `normalized_alias` with the given
136 /// `normalization_certainty`, constrain the inference variable `term` to it
137 /// and return a query response.
138 fn eq_term_and_make_canonical_response(
140 goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
141 normalization_certainty: Certainty,
142 normalized_alias: impl Into<ty::Term<'tcx>>,
143 ) -> QueryResult<'tcx> {
144 // The term of our goal should be fully unconstrained, so this should never fail.
146 // It can however be ambiguous when the `normalized_alias` contains a projection.
147 let nested_goals = self
149 .eq(goal.param_env, goal.predicate.term, normalized_alias.into())
150 .expect("failed to unify with unconstrained term");
152 self.evaluate_all(nested_goals).expect("failed to unify with unconstrained term");
154 self.make_canonical_response(normalization_certainty.unify_and(rhs_certainty))
157 fn merge_project_candidates(
159 mut candidates: Vec<Candidate<'tcx>>,
160 ) -> QueryResult<'tcx> {
161 match candidates.len() {
162 0 => return Err(NoSolution),
163 1 => return Ok(candidates.pop().unwrap().result),
167 if candidates.len() > 1 {
169 'outer: while i < candidates.len() {
170 for j in (0..candidates.len()).filter(|&j| i != j) {
171 if self.project_candidate_should_be_dropped_in_favor_of(
175 debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
176 candidates.swap_remove(i);
181 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
182 // If there are *STILL* multiple candidates, give up
183 // and report ambiguity.
186 debug!("multiple matches, ambig");
187 // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
193 Ok(candidates.pop().unwrap().result)
196 fn project_candidate_should_be_dropped_in_favor_of(
198 candidate: &Candidate<'tcx>,
199 other: &Candidate<'tcx>,
201 // FIXME: implement this
202 match (candidate.source, other.source) {
203 (CandidateSource::Impl(_), _)
204 | (CandidateSource::ParamEnv(_), _)
205 | (CandidateSource::BuiltinImpl, _)
206 | (CandidateSource::AliasBound, _) => unimplemented!(),
211 impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
212 fn self_ty(self) -> Ty<'tcx> {
216 fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
217 self.with_self_ty(tcx, self_ty)
220 fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
221 self.trait_def_id(tcx)
224 fn consider_impl_candidate(
225 ecx: &mut EvalCtxt<'_, 'tcx>,
226 goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
228 ) -> QueryResult<'tcx> {
231 let goal_trait_ref = goal.predicate.projection_ty.trait_ref(tcx);
232 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
233 let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
234 if iter::zip(goal_trait_ref.substs, impl_trait_ref.skip_binder().substs)
235 .any(|(goal, imp)| !drcx.generic_args_may_unify(goal, imp))
237 return Err(NoSolution);
240 ecx.infcx.probe(|_| {
241 let impl_substs = ecx.infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
242 let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
244 let mut nested_goals = ecx.infcx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?;
245 let where_clause_bounds = tcx
246 .predicates_of(impl_def_id)
247 .instantiate(tcx, impl_substs)
250 .map(|pred| goal.with(tcx, pred));
252 nested_goals.extend(where_clause_bounds);
253 let match_impl_certainty = ecx.evaluate_all(nested_goals)?;
255 // In case the associated item is hidden due to specialization, we have to
256 // return ambiguity this would otherwise be incomplete, resulting in
257 // unsoundness during coherence (#105782).
258 let Some(assoc_def) = fetch_eligible_assoc_item_def(
262 goal.predicate.def_id(),
265 return ecx.make_canonical_response(match_impl_certainty.unify_and(Certainty::AMBIGUOUS));
268 if !assoc_def.item.defaultness(tcx).has_value() {
269 tcx.sess.delay_span_bug(
270 tcx.def_span(assoc_def.item.def_id),
271 "missing value for assoc item in impl",
275 // Getting the right substitutions here is complex, e.g. given:
276 // - a goal `<Vec<u32> as Trait<i32>>::Assoc<u64>`
277 // - the applicable impl `impl<T> Trait<i32> for Vec<T>`
278 // - and the impl which defines `Assoc` being `impl<T, U> Trait<U> for Vec<T>`
280 // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]`
283 // And then map these substs to the substs of the defining impl of `Assoc`, going
284 // from `[u32, u64]` to `[u32, i32, u64]`.
285 let impl_substs_with_gat = goal.predicate.projection_ty.substs.rebase_onto(
287 goal_trait_ref.def_id,
290 let substs = translate_substs(
294 impl_substs_with_gat,
295 assoc_def.defining_node,
298 // Finally we construct the actual value of the associated type.
299 let is_const = matches!(tcx.def_kind(assoc_def.item.def_id), DefKind::AssocConst);
300 let ty = tcx.bound_type_of(assoc_def.item.def_id);
301 let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
302 let identity_substs =
303 ty::InternalSubsts::identity_for_item(tcx, assoc_def.item.def_id);
304 let did = ty::WithOptConstParam::unknown(assoc_def.item.def_id);
306 ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
307 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
309 ty.map_bound(|ty| ty.into())
312 ecx.eq_term_and_make_canonical_response(goal, match_impl_certainty, term.subst(tcx, substs))
316 fn consider_assumption(
317 ecx: &mut EvalCtxt<'_, 'tcx>,
318 goal: Goal<'tcx, Self>,
319 assumption: ty::Predicate<'tcx>,
320 ) -> QueryResult<'tcx> {
321 if let Some(poly_projection_pred) = assumption.to_opt_poly_projection_pred()
322 && poly_projection_pred.projection_def_id() == goal.predicate.def_id()
324 ecx.infcx.probe(|_| {
325 let assumption_projection_pred =
326 ecx.infcx.instantiate_binder_with_infer(poly_projection_pred);
327 let nested_goals = ecx.infcx.eq(
329 goal.predicate.projection_ty,
330 assumption_projection_pred.projection_ty,
332 let subst_certainty = ecx.evaluate_all(nested_goals)?;
334 ecx.eq_term_and_make_canonical_response(
337 assumption_projection_pred.term,
345 fn consider_auto_trait_candidate(
346 _ecx: &mut EvalCtxt<'_, 'tcx>,
347 goal: Goal<'tcx, Self>,
348 ) -> QueryResult<'tcx> {
349 bug!("auto traits do not have associated types: {:?}", goal);
352 fn consider_trait_alias_candidate(
353 _ecx: &mut EvalCtxt<'_, 'tcx>,
354 goal: Goal<'tcx, Self>,
355 ) -> QueryResult<'tcx> {
356 bug!("trait aliases do not have associated types: {:?}", goal);
359 fn consider_builtin_sized_candidate(
360 _ecx: &mut EvalCtxt<'_, 'tcx>,
361 goal: Goal<'tcx, Self>,
362 ) -> QueryResult<'tcx> {
363 bug!("`Sized` does not have an associated type: {:?}", goal);
366 fn consider_builtin_copy_clone_candidate(
367 _ecx: &mut EvalCtxt<'_, 'tcx>,
368 goal: Goal<'tcx, Self>,
369 ) -> QueryResult<'tcx> {
370 bug!("`Copy`/`Clone` does not have an associated type: {:?}", goal);
373 fn consider_builtin_pointer_sized_candidate(
374 _ecx: &mut EvalCtxt<'_, 'tcx>,
375 goal: Goal<'tcx, Self>,
376 ) -> QueryResult<'tcx> {
377 bug!("`PointerSized` does not have an associated type: {:?}", goal);
380 fn consider_builtin_fn_trait_candidates(
381 ecx: &mut EvalCtxt<'_, 'tcx>,
382 goal: Goal<'tcx, Self>,
383 goal_kind: ty::ClosureKind,
384 ) -> QueryResult<'tcx> {
385 if let Some(tupled_inputs_and_output) =
386 structural_traits::extract_tupled_inputs_and_output_from_callable(
388 goal.predicate.self_ty(),
392 let pred = tupled_inputs_and_output
393 .map_bound(|(inputs, output)| ty::ProjectionPredicate {
396 .mk_alias_ty(goal.predicate.def_id(), [goal.predicate.self_ty(), inputs]),
399 .to_predicate(ecx.tcx());
400 Self::consider_assumption(ecx, goal, pred)
402 ecx.make_canonical_response(Certainty::AMBIGUOUS)
406 fn consider_builtin_tuple_candidate(
407 _ecx: &mut EvalCtxt<'_, 'tcx>,
408 goal: Goal<'tcx, Self>,
409 ) -> QueryResult<'tcx> {
410 bug!("`Tuple` does not have an associated type: {:?}", goal);
413 fn consider_builtin_pointee_candidate(
414 ecx: &mut EvalCtxt<'_, 'tcx>,
415 goal: Goal<'tcx, Self>,
416 ) -> QueryResult<'tcx> {
418 ecx.infcx.probe(|_| {
419 let metadata_ty = match goal.predicate.self_ty().kind() {
431 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
433 | ty::GeneratorWitness(..)
434 | ty::GeneratorWitnessMIR(..)
436 | ty::Foreign(..) => tcx.types.unit,
438 ty::Error(e) => tcx.ty_error_with_guaranteed(*e),
440 ty::Str | ty::Slice(_) => tcx.types.usize,
442 ty::Dynamic(_, _, _) => {
443 let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, None);
444 tcx.bound_type_of(dyn_metadata)
445 .subst(tcx, &[ty::GenericArg::from(goal.predicate.self_ty())])
448 ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => {
449 // FIXME(ptr_metadata): It would also be possible to return a `Ok(Ambig)` with no constraints.
450 let sized_predicate = ty::Binder::dummy(tcx.at(DUMMY_SP).mk_trait_ref(
452 [ty::GenericArg::from(goal.predicate.self_ty())],
455 let is_sized_certainty = ecx.evaluate_goal(goal.with(tcx, sized_predicate))?.1;
456 return ecx.eq_term_and_make_canonical_response(
463 ty::Adt(def, substs) if def.is_struct() => {
464 match def.non_enum_variant().fields.last() {
465 None => tcx.types.unit,
467 let self_ty = field_def.ty(tcx, substs);
468 let new_goal = goal.with(
470 ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)),
472 let (_, certainty) = ecx.evaluate_goal(new_goal)?;
473 return ecx.make_canonical_response(certainty);
477 ty::Adt(_, _) => tcx.types.unit,
479 ty::Tuple(elements) => match elements.last() {
480 None => tcx.types.unit,
482 let new_goal = goal.with(
484 ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)),
486 let (_, certainty) = ecx.evaluate_goal(new_goal)?;
487 return ecx.make_canonical_response(certainty);
492 ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_),
494 | ty::Bound(..) => bug!(
495 "unexpected self ty `{:?}` when normalizing `<T as Pointee>::Metadata`",
496 goal.predicate.self_ty()
500 ecx.eq_term_and_make_canonical_response(goal, Certainty::Yes, metadata_ty)
504 fn consider_builtin_future_candidate(
505 ecx: &mut EvalCtxt<'_, 'tcx>,
506 goal: Goal<'tcx, Self>,
507 ) -> QueryResult<'tcx> {
508 let self_ty = goal.predicate.self_ty();
509 let ty::Generator(def_id, substs, _) = *self_ty.kind() else {
510 return Err(NoSolution);
513 // Generators are not futures unless they come from `async` desugaring
515 if !tcx.generator_is_async(def_id) {
516 return Err(NoSolution);
519 let term = substs.as_generator().return_ty().into();
521 Self::consider_assumption(
524 ty::Binder::dummy(ty::ProjectionPredicate {
525 projection_ty: ecx.tcx().mk_alias_ty(goal.predicate.def_id(), [self_ty]),
532 fn consider_builtin_generator_candidate(
533 ecx: &mut EvalCtxt<'_, 'tcx>,
534 goal: Goal<'tcx, Self>,
535 ) -> QueryResult<'tcx> {
536 let self_ty = goal.predicate.self_ty();
537 let ty::Generator(def_id, substs, _) = *self_ty.kind() else {
538 return Err(NoSolution);
541 // `async`-desugared generators do not implement the generator trait
543 if tcx.generator_is_async(def_id) {
544 return Err(NoSolution);
547 let generator = substs.as_generator();
549 let name = tcx.associated_item(goal.predicate.def_id()).name;
550 let term = if name == sym::Return {
551 generator.return_ty().into()
552 } else if name == sym::Yield {
553 generator.yield_ty().into()
555 bug!("unexpected associated item `<{self_ty} as Generator>::{name}`")
558 Self::consider_assumption(
561 ty::Binder::dummy(ty::ProjectionPredicate {
564 .mk_alias_ty(goal.predicate.def_id(), [self_ty, generator.resume_ty()]),
571 fn consider_builtin_unsize_candidate(
572 _ecx: &mut EvalCtxt<'_, 'tcx>,
573 goal: Goal<'tcx, Self>,
574 ) -> QueryResult<'tcx> {
575 bug!("`Unsize` does not have an associated type: {:?}", goal);
578 fn consider_builtin_dyn_upcast_candidates(
579 _ecx: &mut EvalCtxt<'_, 'tcx>,
580 goal: Goal<'tcx, Self>,
581 ) -> Vec<super::CanonicalResponse<'tcx>> {
582 bug!("`Unsize` does not have an associated type: {:?}", goal);
585 fn consider_builtin_discriminant_kind_candidate(
586 ecx: &mut EvalCtxt<'_, 'tcx>,
587 goal: Goal<'tcx, Self>,
588 ) -> QueryResult<'tcx> {
589 let discriminant = goal.predicate.self_ty().discriminant_ty(ecx.tcx());
591 .probe(|_| ecx.eq_term_and_make_canonical_response(goal, Certainty::Yes, discriminant))
595 /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code.
597 /// FIXME: We should merge these 3 implementations as it's likely that they otherwise
599 #[instrument(level = "debug", skip(infcx, param_env), ret)]
600 fn fetch_eligible_assoc_item_def<'tcx>(
601 infcx: &InferCtxt<'tcx>,
602 param_env: ty::ParamEnv<'tcx>,
603 goal_trait_ref: ty::TraitRef<'tcx>,
604 trait_assoc_def_id: DefId,
606 ) -> Result<Option<LeafDef>, NoSolution> {
607 let node_item = specialization_graph::assoc_def(infcx.tcx, impl_def_id, trait_assoc_def_id)
608 .map_err(|ErrorGuaranteed { .. }| NoSolution)?;
610 let eligible = if node_item.is_final() {
611 // Non-specializable items are always projectable.
614 // Only reveal a specializable default if we're past type-checking
615 // and the obligation is monomorphic, otherwise passes such as
616 // transmute checking and polymorphic MIR optimizations could
617 // get a result which isn't correct for all monomorphizations.
618 if param_env.reveal() == Reveal::All {
619 let poly_trait_ref = infcx.resolve_vars_if_possible(goal_trait_ref);
620 !poly_trait_ref.still_further_specializable()
622 debug!(?node_item.item.def_id, "not eligible due to default");
627 if eligible { Ok(Some(node_item)) } else { Ok(None) }