]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/solve/project_goals.rs
Rollup merge of #107780 - compiler-errors:instantiate-binder, r=lcnr
[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_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};
20 use std::iter;
21 use std::ops::ControlFlow;
22
23 impl<'tcx> EvalCtxt<'_, 'tcx> {
24     pub(super) fn compute_projection_goal(
25         &mut self,
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.
30         //
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)
38         } else {
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(),
43             };
44             let unconstrained_predicate = ty::Clause::Projection(ProjectionPredicate {
45                 projection_ty: goal.predicate.projection_ty,
46                 term: unconstrained_rhs,
47             });
48             let (_has_changed, normalize_certainty) = self.in_projection_eq_hack(|this| {
49                 this.evaluate_goal(goal.with(this.tcx(), unconstrained_predicate))
50             })?;
51
52             let nested_eq_goals =
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))
56         }
57     }
58
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;
63         let result = f(self);
64         self.in_projection_eq_hack = false;
65         result
66     }
67
68     /// Is the projection predicate is of the form `exists<T> <Ty as Trait>::Assoc = T`.
69     ///
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(),
80                     }
81                 } else {
82                     false
83                 }
84             }
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(),
90                     }
91                 } else {
92                     false
93                 }
94             }
95         };
96
97         // Guard against `<T as Trait<?0>>::Assoc = ?0>`.
98         struct ContainsTerm<'tcx> {
99             term: ty::Term<'tcx>,
100         }
101         impl<'tcx> TypeVisitor<'tcx> for ContainsTerm<'tcx> {
102             type BreakTy = ();
103             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
104                 if t.needs_infer() {
105                     if ty::Term::from(t) == self.term {
106                         ControlFlow::Break(())
107                     } else {
108                         t.super_visit_with(self)
109                     }
110                 } else {
111                     ControlFlow::Continue(())
112                 }
113             }
114
115             fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
116                 if c.needs_infer() {
117                     if ty::Term::from(c) == self.term {
118                         ControlFlow::Break(())
119                     } else {
120                         c.super_visit_with(self)
121                     }
122                 } else {
123                     ControlFlow::Continue(())
124                 }
125             }
126         }
127
128         let mut visitor = ContainsTerm { term: goal.predicate.term };
129
130         term_is_infer
131             && goal.predicate.projection_ty.visit_with(&mut visitor).is_continue()
132             && goal.param_env.visit_with(&mut visitor).is_continue()
133     }
134
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(
139         &mut self,
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.
145         //
146         // It can however be ambiguous when the `normalized_alias` contains a projection.
147         let nested_goals = self
148             .infcx
149             .eq(goal.param_env, goal.predicate.term, normalized_alias.into())
150             .expect("failed to unify with unconstrained term");
151         let rhs_certainty =
152             self.evaluate_all(nested_goals).expect("failed to unify with unconstrained term");
153
154         self.make_canonical_response(normalization_certainty.unify_and(rhs_certainty))
155     }
156
157     fn merge_project_candidates(
158         &mut self,
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),
164             _ => {}
165         }
166
167         if candidates.len() > 1 {
168             let mut i = 0;
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(
172                         &candidates[i],
173                         &candidates[j],
174                     ) {
175                         debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
176                         candidates.swap_remove(i);
177                         continue 'outer;
178                     }
179                 }
180
181                 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
182                 // If there are *STILL* multiple candidates, give up
183                 // and report ambiguity.
184                 i += 1;
185                 if i > 1 {
186                     debug!("multiple matches, ambig");
187                     // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
188                     unimplemented!();
189                 }
190             }
191         }
192
193         Ok(candidates.pop().unwrap().result)
194     }
195
196     fn project_candidate_should_be_dropped_in_favor_of(
197         &self,
198         candidate: &Candidate<'tcx>,
199         other: &Candidate<'tcx>,
200     ) -> bool {
201         // FIXME: implement this
202         match (candidate.source, other.source) {
203             (CandidateSource::Impl(_), _)
204             | (CandidateSource::ParamEnv(_), _)
205             | (CandidateSource::BuiltinImpl, _)
206             | (CandidateSource::AliasBound, _) => unimplemented!(),
207         }
208     }
209 }
210
211 impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
212     fn self_ty(self) -> Ty<'tcx> {
213         self.self_ty()
214     }
215
216     fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
217         self.with_self_ty(tcx, self_ty)
218     }
219
220     fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
221         self.trait_def_id(tcx)
222     }
223
224     fn consider_impl_candidate(
225         ecx: &mut EvalCtxt<'_, 'tcx>,
226         goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
227         impl_def_id: DefId,
228     ) -> QueryResult<'tcx> {
229         let tcx = ecx.tcx();
230
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))
236         {
237             return Err(NoSolution);
238         }
239
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);
243
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)
248                 .predicates
249                 .into_iter()
250                 .map(|pred| goal.with(tcx, pred));
251
252             nested_goals.extend(where_clause_bounds);
253             let match_impl_certainty = ecx.evaluate_all(nested_goals)?;
254
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(
259                 ecx.infcx,
260                 goal.param_env,
261                 goal_trait_ref,
262                 goal.predicate.def_id(),
263                 impl_def_id
264             )? else {
265                 return ecx.make_canonical_response(match_impl_certainty.unify_and(Certainty::AMBIGUOUS));
266             };
267
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",
272                 );
273             }
274
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>`
279             //
280             // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]`
281             // to `[u32, u64]`.
282             //
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(
286                 tcx,
287                 goal_trait_ref.def_id,
288                 impl_substs,
289             );
290             let substs = translate_substs(
291                 ecx.infcx,
292                 goal.param_env,
293                 impl_def_id,
294                 impl_substs_with_gat,
295                 assoc_def.defining_node,
296             );
297
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);
305                 let kind =
306                     ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
307                 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
308             } else {
309                 ty.map_bound(|ty| ty.into())
310             };
311
312             ecx.eq_term_and_make_canonical_response(goal, match_impl_certainty, term.subst(tcx, substs))
313         })
314     }
315
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()
323         {
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(
328                     goal.param_env,
329                     goal.predicate.projection_ty,
330                     assumption_projection_pred.projection_ty,
331                 )?;
332                 let subst_certainty = ecx.evaluate_all(nested_goals)?;
333
334                 ecx.eq_term_and_make_canonical_response(
335                     goal,
336                     subst_certainty,
337                     assumption_projection_pred.term,
338                 )
339             })
340         } else {
341             Err(NoSolution)
342         }
343     }
344
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);
350     }
351
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);
357     }
358
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);
364     }
365
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);
371     }
372
373     fn consider_builtin_pointer_like_candidate(
374         _ecx: &mut EvalCtxt<'_, 'tcx>,
375         goal: Goal<'tcx, Self>,
376     ) -> QueryResult<'tcx> {
377         bug!("`PointerLike` does not have an associated type: {:?}", goal);
378     }
379
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(
387                 ecx.tcx(),
388                 goal.predicate.self_ty(),
389                 goal_kind,
390             )?
391         {
392             let pred = tupled_inputs_and_output
393                 .map_bound(|(inputs, output)| ty::ProjectionPredicate {
394                     projection_ty: ecx
395                         .tcx()
396                         .mk_alias_ty(goal.predicate.def_id(), [goal.predicate.self_ty(), inputs]),
397                     term: output.into(),
398                 })
399                 .to_predicate(ecx.tcx());
400             Self::consider_assumption(ecx, goal, pred)
401         } else {
402             ecx.make_canonical_response(Certainty::AMBIGUOUS)
403         }
404     }
405
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);
411     }
412
413     fn consider_builtin_pointee_candidate(
414         ecx: &mut EvalCtxt<'_, 'tcx>,
415         goal: Goal<'tcx, Self>,
416     ) -> QueryResult<'tcx> {
417         let tcx = ecx.tcx();
418         ecx.infcx.probe(|_| {
419             let metadata_ty = match goal.predicate.self_ty().kind() {
420                 ty::Bool
421                 | ty::Char
422                 | ty::Int(..)
423                 | ty::Uint(..)
424                 | ty::Float(..)
425                 | ty::Array(..)
426                 | ty::RawPtr(..)
427                 | ty::Ref(..)
428                 | ty::FnDef(..)
429                 | ty::FnPtr(..)
430                 | ty::Closure(..)
431                 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
432                 | ty::Generator(..)
433                 | ty::GeneratorWitness(..)
434                 | ty::GeneratorWitnessMIR(..)
435                 | ty::Never
436                 | ty::Foreign(..) => tcx.types.unit,
437
438                 ty::Error(e) => tcx.ty_error_with_guaranteed(*e),
439
440                 ty::Str | ty::Slice(_) => tcx.types.usize,
441
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())])
446                 }
447
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(
451                         LangItem::Sized,
452                         [ty::GenericArg::from(goal.predicate.self_ty())],
453                     ));
454
455                     let is_sized_certainty = ecx.evaluate_goal(goal.with(tcx, sized_predicate))?.1;
456                     return ecx.eq_term_and_make_canonical_response(
457                         goal,
458                         is_sized_certainty,
459                         tcx.types.unit,
460                     );
461                 }
462
463                 ty::Adt(def, substs) if def.is_struct() => {
464                     match def.non_enum_variant().fields.last() {
465                         None => tcx.types.unit,
466                         Some(field_def) => {
467                             let self_ty = field_def.ty(tcx, substs);
468                             let new_goal = goal.with(
469                                 tcx,
470                                 ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)),
471                             );
472                             let (_, certainty) = ecx.evaluate_goal(new_goal)?;
473                             return ecx.make_canonical_response(certainty);
474                         }
475                     }
476                 }
477                 ty::Adt(_, _) => tcx.types.unit,
478
479                 ty::Tuple(elements) => match elements.last() {
480                     None => tcx.types.unit,
481                     Some(&self_ty) => {
482                         let new_goal = goal.with(
483                             tcx,
484                             ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)),
485                         );
486                         let (_, certainty) = ecx.evaluate_goal(new_goal)?;
487                         return ecx.make_canonical_response(certainty);
488                     }
489                 },
490
491                 ty::Infer(
492                     ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_),
493                 )
494                 | ty::Bound(..) => bug!(
495                     "unexpected self ty `{:?}` when normalizing `<T as Pointee>::Metadata`",
496                     goal.predicate.self_ty()
497                 ),
498             };
499
500             ecx.eq_term_and_make_canonical_response(goal, Certainty::Yes, metadata_ty)
501         })
502     }
503
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);
511         };
512
513         // Generators are not futures unless they come from `async` desugaring
514         let tcx = ecx.tcx();
515         if !tcx.generator_is_async(def_id) {
516             return Err(NoSolution);
517         }
518
519         let term = substs.as_generator().return_ty().into();
520
521         Self::consider_assumption(
522             ecx,
523             goal,
524             ty::Binder::dummy(ty::ProjectionPredicate {
525                 projection_ty: ecx.tcx().mk_alias_ty(goal.predicate.def_id(), [self_ty]),
526                 term,
527             })
528             .to_predicate(tcx),
529         )
530     }
531
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);
539         };
540
541         // `async`-desugared generators do not implement the generator trait
542         let tcx = ecx.tcx();
543         if tcx.generator_is_async(def_id) {
544             return Err(NoSolution);
545         }
546
547         let generator = substs.as_generator();
548
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()
554         } else {
555             bug!("unexpected associated item `<{self_ty} as Generator>::{name}`")
556         };
557
558         Self::consider_assumption(
559             ecx,
560             goal,
561             ty::Binder::dummy(ty::ProjectionPredicate {
562                 projection_ty: ecx
563                     .tcx()
564                     .mk_alias_ty(goal.predicate.def_id(), [self_ty, generator.resume_ty()]),
565                 term,
566             })
567             .to_predicate(tcx),
568         )
569     }
570
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);
576     }
577
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);
583     }
584
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());
590         ecx.infcx
591             .probe(|_| ecx.eq_term_and_make_canonical_response(goal, Certainty::Yes, discriminant))
592     }
593 }
594
595 /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code.
596 ///
597 /// FIXME: We should merge these 3 implementations as it's likely that they otherwise
598 /// diverge.
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,
605     impl_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)?;
609
610     let eligible = if node_item.is_final() {
611         // Non-specializable items are always projectable.
612         true
613     } else {
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()
621         } else {
622             debug!(?node_item.item.def_id, "not eligible due to default");
623             false
624         }
625     };
626
627     if eligible { Ok(Some(node_item)) } else { Ok(None) }
628 }