]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/solve/project_goals.rs
879f18843c9171def566dea30e95cf45e33d6d4c
[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) =
49                 self.evaluate_goal(goal.with(self.tcx(), unconstrained_predicate))?;
50
51             let nested_eq_goals =
52                 self.infcx.eq(goal.param_env, unconstrained_rhs, predicate.term)?;
53             let eval_certainty = self.evaluate_all(nested_eq_goals)?;
54             self.make_canonical_response(normalize_certainty.unify_and(eval_certainty))
55         }
56     }
57
58     /// Is the projection predicate is of the form `exists<T> <Ty as Trait>::Assoc = T`.
59     ///
60     /// This is the case if the `term` is an inference variable in the innermost universe
61     /// and does not occur in any other part of the predicate.
62     fn term_is_fully_unconstrained(&self, goal: Goal<'tcx, ProjectionPredicate<'tcx>>) -> bool {
63         let infcx = self.infcx;
64         let term_is_infer = match goal.predicate.term.unpack() {
65             ty::TermKind::Ty(ty) => {
66                 if let &ty::Infer(ty::TyVar(vid)) = ty.kind() {
67                     match infcx.probe_ty_var(vid) {
68                         Ok(value) => bug!("resolved var in query: {goal:?} {value:?}"),
69                         Err(universe) => universe == infcx.universe(),
70                     }
71                 } else {
72                     false
73                 }
74             }
75             ty::TermKind::Const(ct) => {
76                 if let ty::ConstKind::Infer(ty::InferConst::Var(vid)) = ct.kind() {
77                     match self.infcx.probe_const_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         };
86
87         // Guard against `<T as Trait<?0>>::Assoc = ?0>`.
88         struct ContainsTerm<'tcx> {
89             term: ty::Term<'tcx>,
90         }
91         impl<'tcx> TypeVisitor<'tcx> for ContainsTerm<'tcx> {
92             type BreakTy = ();
93             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
94                 if t.needs_infer() {
95                     if ty::Term::from(t) == self.term {
96                         ControlFlow::Break(())
97                     } else {
98                         t.super_visit_with(self)
99                     }
100                 } else {
101                     ControlFlow::Continue(())
102                 }
103             }
104
105             fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
106                 if c.needs_infer() {
107                     if ty::Term::from(c) == self.term {
108                         ControlFlow::Break(())
109                     } else {
110                         c.super_visit_with(self)
111                     }
112                 } else {
113                     ControlFlow::Continue(())
114                 }
115             }
116         }
117
118         let mut visitor = ContainsTerm { term: goal.predicate.term };
119
120         term_is_infer
121             && goal.predicate.projection_ty.visit_with(&mut visitor).is_continue()
122             && goal.param_env.visit_with(&mut visitor).is_continue()
123     }
124
125     fn merge_project_candidates(
126         &mut self,
127         mut candidates: Vec<Candidate<'tcx>>,
128     ) -> QueryResult<'tcx> {
129         match candidates.len() {
130             0 => return Err(NoSolution),
131             1 => return Ok(candidates.pop().unwrap().result),
132             _ => {}
133         }
134
135         if candidates.len() > 1 {
136             let mut i = 0;
137             'outer: while i < candidates.len() {
138                 for j in (0..candidates.len()).filter(|&j| i != j) {
139                     if self.project_candidate_should_be_dropped_in_favor_of(
140                         &candidates[i],
141                         &candidates[j],
142                     ) {
143                         debug!(candidate = ?candidates[i], "Dropping candidate #{}/{}", i, candidates.len());
144                         candidates.swap_remove(i);
145                         continue 'outer;
146                     }
147                 }
148
149                 debug!(candidate = ?candidates[i], "Retaining candidate #{}/{}", i, candidates.len());
150                 // If there are *STILL* multiple candidates, give up
151                 // and report ambiguity.
152                 i += 1;
153                 if i > 1 {
154                     debug!("multiple matches, ambig");
155                     // FIXME: return overflow if all candidates overflow, otherwise return ambiguity.
156                     unimplemented!();
157                 }
158             }
159         }
160
161         Ok(candidates.pop().unwrap().result)
162     }
163
164     fn project_candidate_should_be_dropped_in_favor_of(
165         &self,
166         candidate: &Candidate<'tcx>,
167         other: &Candidate<'tcx>,
168     ) -> bool {
169         // FIXME: implement this
170         match (candidate.source, other.source) {
171             (CandidateSource::Impl(_), _)
172             | (CandidateSource::ParamEnv(_), _)
173             | (CandidateSource::BuiltinImpl, _)
174             | (CandidateSource::AliasBound, _) => unimplemented!(),
175         }
176     }
177 }
178
179 impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> {
180     fn self_ty(self) -> Ty<'tcx> {
181         self.self_ty()
182     }
183
184     fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
185         self.with_self_ty(tcx, self_ty)
186     }
187
188     fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
189         self.trait_def_id(tcx)
190     }
191
192     fn consider_impl_candidate(
193         ecx: &mut EvalCtxt<'_, 'tcx>,
194         goal: Goal<'tcx, ProjectionPredicate<'tcx>>,
195         impl_def_id: DefId,
196     ) -> QueryResult<'tcx> {
197         let tcx = ecx.tcx();
198
199         let goal_trait_ref = goal.predicate.projection_ty.trait_ref(tcx);
200         let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
201         let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsPlaceholder };
202         if iter::zip(goal_trait_ref.substs, impl_trait_ref.skip_binder().substs)
203             .any(|(goal, imp)| !drcx.generic_args_may_unify(goal, imp))
204         {
205             return Err(NoSolution);
206         }
207
208         ecx.infcx.probe(|_| {
209             let impl_substs = ecx.infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id);
210             let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs);
211
212             let mut nested_goals = ecx.infcx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?;
213             let where_clause_bounds = tcx
214                 .predicates_of(impl_def_id)
215                 .instantiate(tcx, impl_substs)
216                 .predicates
217                 .into_iter()
218                 .map(|pred| goal.with(tcx, pred));
219
220             nested_goals.extend(where_clause_bounds);
221             let trait_ref_certainty = ecx.evaluate_all(nested_goals)?;
222
223             // In case the associated item is hidden due to specialization, we have to
224             // return ambiguity this would otherwise be incomplete, resulting in
225             // unsoundness during coherence (#105782).
226             let Some(assoc_def) = fetch_eligible_assoc_item_def(
227                 ecx.infcx,
228                 goal.param_env,
229                 goal_trait_ref,
230                 goal.predicate.def_id(),
231                 impl_def_id
232             )? else {
233                 return ecx.make_canonical_response(trait_ref_certainty.unify_and(Certainty::AMBIGUOUS));
234             };
235
236             if !assoc_def.item.defaultness(tcx).has_value() {
237                 tcx.sess.delay_span_bug(
238                     tcx.def_span(assoc_def.item.def_id),
239                     "missing value for assoc item in impl",
240                 );
241             }
242
243             // Getting the right substitutions here is complex, e.g. given:
244             // - a goal `<Vec<u32> as Trait<i32>>::Assoc<u64>`
245             // - the applicable impl `impl<T> Trait<i32> for Vec<T>`
246             // - and the impl which defines `Assoc` being `impl<T, U> Trait<U> for Vec<T>`
247             //
248             // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]`
249             // to `[u32, u64]`.
250             //
251             // And then map these substs to the substs of the defining impl of `Assoc`, going
252             // from `[u32, u64]` to `[u32, i32, u64]`.
253             let impl_substs_with_gat = goal.predicate.projection_ty.substs.rebase_onto(
254                 tcx,
255                 goal_trait_ref.def_id,
256                 impl_substs,
257             );
258             let substs = translate_substs(
259                 ecx.infcx,
260                 goal.param_env,
261                 impl_def_id,
262                 impl_substs_with_gat,
263                 assoc_def.defining_node,
264             );
265
266             // Finally we construct the actual value of the associated type.
267             let is_const = matches!(tcx.def_kind(assoc_def.item.def_id), DefKind::AssocConst);
268             let ty = tcx.bound_type_of(assoc_def.item.def_id);
269             let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const {
270                 let identity_substs =
271                     ty::InternalSubsts::identity_for_item(tcx, assoc_def.item.def_id);
272                 let did = ty::WithOptConstParam::unknown(assoc_def.item.def_id);
273                 let kind =
274                     ty::ConstKind::Unevaluated(ty::UnevaluatedConst::new(did, identity_substs));
275                 ty.map_bound(|ty| tcx.mk_const(kind, ty).into())
276             } else {
277                 ty.map_bound(|ty| ty.into())
278             };
279
280             // The term of our goal should be fully unconstrained, so this should never fail.
281             //
282             // It can however be ambiguous when the resolved type is a projection.
283             let nested_goals = ecx
284                 .infcx
285                 .eq(goal.param_env, goal.predicate.term, term.subst(tcx, substs))
286                 .expect("failed to unify with unconstrained term");
287             let rhs_certainty =
288                 ecx.evaluate_all(nested_goals).expect("failed to unify with unconstrained term");
289
290             ecx.make_canonical_response(trait_ref_certainty.unify_and(rhs_certainty))
291         })
292     }
293
294     fn consider_assumption(
295         ecx: &mut EvalCtxt<'_, 'tcx>,
296         goal: Goal<'tcx, Self>,
297         assumption: ty::Predicate<'tcx>,
298     ) -> QueryResult<'tcx> {
299         if let Some(poly_projection_pred) = assumption.to_opt_poly_projection_pred()
300             && poly_projection_pred.projection_def_id() == goal.predicate.def_id()
301         {
302             ecx.infcx.probe(|_| {
303                 let assumption_projection_pred =
304                     ecx.infcx.instantiate_bound_vars_with_infer(poly_projection_pred);
305                 let nested_goals = ecx.infcx.eq(
306                     goal.param_env,
307                     goal.predicate.projection_ty,
308                     assumption_projection_pred.projection_ty,
309                 )?;
310                 let subst_certainty = ecx.evaluate_all(nested_goals)?;
311
312                 // The term of our goal should be fully unconstrained, so this should never fail.
313                 //
314                 // It can however be ambiguous when the resolved type is a projection.
315                 let nested_goals = ecx
316                     .infcx
317                     .eq(goal.param_env, goal.predicate.term, assumption_projection_pred.term)
318                     .expect("failed to unify with unconstrained term");
319                 let rhs_certainty = ecx
320                     .evaluate_all(nested_goals)
321                     .expect("failed to unify with unconstrained term");
322
323                 ecx.make_canonical_response(subst_certainty.unify_and(rhs_certainty))
324             })
325         } else {
326             Err(NoSolution)
327         }
328     }
329
330     fn consider_auto_trait_candidate(
331         _ecx: &mut EvalCtxt<'_, 'tcx>,
332         goal: Goal<'tcx, Self>,
333     ) -> QueryResult<'tcx> {
334         bug!("auto traits do not have associated types: {:?}", goal);
335     }
336
337     fn consider_trait_alias_candidate(
338         _ecx: &mut EvalCtxt<'_, 'tcx>,
339         goal: Goal<'tcx, Self>,
340     ) -> QueryResult<'tcx> {
341         bug!("trait aliases do not have associated types: {:?}", goal);
342     }
343
344     fn consider_builtin_sized_candidate(
345         _ecx: &mut EvalCtxt<'_, 'tcx>,
346         goal: Goal<'tcx, Self>,
347     ) -> QueryResult<'tcx> {
348         bug!("`Sized` does not have an associated type: {:?}", goal);
349     }
350
351     fn consider_builtin_copy_clone_candidate(
352         _ecx: &mut EvalCtxt<'_, 'tcx>,
353         goal: Goal<'tcx, Self>,
354     ) -> QueryResult<'tcx> {
355         bug!("`Copy`/`Clone` does not have an associated type: {:?}", goal);
356     }
357
358     fn consider_builtin_pointer_sized_candidate(
359         _ecx: &mut EvalCtxt<'_, 'tcx>,
360         goal: Goal<'tcx, Self>,
361     ) -> QueryResult<'tcx> {
362         bug!("`PointerSized` does not have an associated type: {:?}", goal);
363     }
364
365     fn consider_builtin_fn_trait_candidates(
366         ecx: &mut EvalCtxt<'_, 'tcx>,
367         goal: Goal<'tcx, Self>,
368         goal_kind: ty::ClosureKind,
369     ) -> QueryResult<'tcx> {
370         if let Some(tupled_inputs_and_output) =
371             structural_traits::extract_tupled_inputs_and_output_from_callable(
372                 ecx.tcx(),
373                 goal.predicate.self_ty(),
374                 goal_kind,
375             )?
376         {
377             let pred = tupled_inputs_and_output
378                 .map_bound(|(inputs, output)| ty::ProjectionPredicate {
379                     projection_ty: ecx
380                         .tcx()
381                         .mk_alias_ty(goal.predicate.def_id(), [goal.predicate.self_ty(), inputs]),
382                     term: output.into(),
383                 })
384                 .to_predicate(ecx.tcx());
385             Self::consider_assumption(ecx, goal, pred)
386         } else {
387             ecx.make_canonical_response(Certainty::AMBIGUOUS)
388         }
389     }
390
391     fn consider_builtin_tuple_candidate(
392         _ecx: &mut EvalCtxt<'_, 'tcx>,
393         goal: Goal<'tcx, Self>,
394     ) -> QueryResult<'tcx> {
395         bug!("`Tuple` does not have an associated type: {:?}", goal);
396     }
397
398     fn consider_builtin_pointee_candidate(
399         ecx: &mut EvalCtxt<'_, 'tcx>,
400         goal: Goal<'tcx, Self>,
401     ) -> QueryResult<'tcx> {
402         let tcx = ecx.tcx();
403         ecx.infcx.probe(|_| {
404             let metadata_ty = match goal.predicate.self_ty().kind() {
405                 ty::Bool
406                 | ty::Char
407                 | ty::Int(..)
408                 | ty::Uint(..)
409                 | ty::Float(..)
410                 | ty::Array(..)
411                 | ty::RawPtr(..)
412                 | ty::Ref(..)
413                 | ty::FnDef(..)
414                 | ty::FnPtr(..)
415                 | ty::Closure(..)
416                 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..))
417                 | ty::Generator(..)
418                 | ty::GeneratorWitness(..)
419                 | ty::GeneratorWitnessMIR(..)
420                 | ty::Never
421                 | ty::Foreign(..) => tcx.types.unit,
422
423                 ty::Error(e) => tcx.ty_error_with_guaranteed(*e),
424
425                 ty::Str | ty::Slice(_) => tcx.types.usize,
426
427                 ty::Dynamic(_, _, _) => {
428                     let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, None);
429                     tcx.bound_type_of(dyn_metadata)
430                         .subst(tcx, &[ty::GenericArg::from(goal.predicate.self_ty())])
431                 }
432
433                 ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => {
434                     // FIXME(ptr_metadata): It would also be possible to return a `Ok(Ambig)` with no constraints.
435                     let sized_predicate = ty::Binder::dummy(tcx.at(DUMMY_SP).mk_trait_ref(
436                         LangItem::Sized,
437                         [ty::GenericArg::from(goal.predicate.self_ty())],
438                     ));
439
440                     let mut nested_goals = ecx.infcx.eq(
441                         goal.param_env,
442                         goal.predicate.term.ty().unwrap(),
443                         tcx.types.unit,
444                     )?;
445                     nested_goals.push(goal.with(tcx, sized_predicate));
446
447                     return ecx.evaluate_all_and_make_canonical_response(nested_goals);
448                 }
449
450                 ty::Adt(def, substs) if def.is_struct() => {
451                     match def.non_enum_variant().fields.last() {
452                         None => tcx.types.unit,
453                         Some(field_def) => {
454                             let self_ty = field_def.ty(tcx, substs);
455                             let new_goal = goal.with(
456                                 tcx,
457                                 ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)),
458                             );
459                             return ecx.evaluate_all_and_make_canonical_response(vec![new_goal]);
460                         }
461                     }
462                 }
463                 ty::Adt(_, _) => tcx.types.unit,
464
465                 ty::Tuple(elements) => match elements.last() {
466                     None => tcx.types.unit,
467                     Some(&self_ty) => {
468                         let new_goal = goal.with(
469                             tcx,
470                             ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)),
471                         );
472                         return ecx.evaluate_all_and_make_canonical_response(vec![new_goal]);
473                     }
474                 },
475
476                 ty::Infer(
477                     ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_),
478                 )
479                 | ty::Bound(..) => bug!(
480                     "unexpected self ty `{:?}` when normalizing `<T as Pointee>::Metadata`",
481                     goal.predicate.self_ty()
482                 ),
483             };
484
485             let nested_goals =
486                 ecx.infcx.eq(goal.param_env, goal.predicate.term.ty().unwrap(), metadata_ty)?;
487             ecx.evaluate_all_and_make_canonical_response(nested_goals)
488         })
489     }
490
491     fn consider_builtin_future_candidate(
492         ecx: &mut EvalCtxt<'_, 'tcx>,
493         goal: Goal<'tcx, Self>,
494     ) -> QueryResult<'tcx> {
495         let self_ty = goal.predicate.self_ty();
496         let ty::Generator(def_id, substs, _) = *self_ty.kind() else {
497             return Err(NoSolution);
498         };
499
500         // Generators are not futures unless they come from `async` desugaring
501         let tcx = ecx.tcx();
502         if !tcx.generator_is_async(def_id) {
503             return Err(NoSolution);
504         }
505
506         let term = substs.as_generator().return_ty().into();
507
508         Self::consider_assumption(
509             ecx,
510             goal,
511             ty::Binder::dummy(ty::ProjectionPredicate {
512                 projection_ty: ecx.tcx().mk_alias_ty(goal.predicate.def_id(), [self_ty]),
513                 term,
514             })
515             .to_predicate(tcx),
516         )
517     }
518
519     fn consider_builtin_generator_candidate(
520         ecx: &mut EvalCtxt<'_, 'tcx>,
521         goal: Goal<'tcx, Self>,
522     ) -> QueryResult<'tcx> {
523         let self_ty = goal.predicate.self_ty();
524         let ty::Generator(def_id, substs, _) = *self_ty.kind() else {
525             return Err(NoSolution);
526         };
527
528         // `async`-desugared generators do not implement the generator trait
529         let tcx = ecx.tcx();
530         if tcx.generator_is_async(def_id) {
531             return Err(NoSolution);
532         }
533
534         let generator = substs.as_generator();
535
536         let name = tcx.associated_item(goal.predicate.def_id()).name;
537         let term = if name == sym::Return {
538             generator.return_ty().into()
539         } else if name == sym::Yield {
540             generator.yield_ty().into()
541         } else {
542             bug!("unexpected associated item `<{self_ty} as Generator>::{name}`")
543         };
544
545         Self::consider_assumption(
546             ecx,
547             goal,
548             ty::Binder::dummy(ty::ProjectionPredicate {
549                 projection_ty: ecx
550                     .tcx()
551                     .mk_alias_ty(goal.predicate.def_id(), [self_ty, generator.resume_ty()]),
552                 term,
553             })
554             .to_predicate(tcx),
555         )
556     }
557
558     fn consider_builtin_unsize_candidate(
559         _ecx: &mut EvalCtxt<'_, 'tcx>,
560         goal: Goal<'tcx, Self>,
561     ) -> QueryResult<'tcx> {
562         bug!("`Unsize` does not have an associated type: {:?}", goal);
563     }
564
565     fn consider_builtin_dyn_upcast_candidates(
566         _ecx: &mut EvalCtxt<'_, 'tcx>,
567         goal: Goal<'tcx, Self>,
568     ) -> Vec<super::CanonicalResponse<'tcx>> {
569         bug!("`Unsize` does not have an associated type: {:?}", goal);
570     }
571 }
572
573 /// This behavior is also implemented in `rustc_ty_utils` and in the old `project` code.
574 ///
575 /// FIXME: We should merge these 3 implementations as it's likely that they otherwise
576 /// diverge.
577 #[instrument(level = "debug", skip(infcx, param_env), ret)]
578 fn fetch_eligible_assoc_item_def<'tcx>(
579     infcx: &InferCtxt<'tcx>,
580     param_env: ty::ParamEnv<'tcx>,
581     goal_trait_ref: ty::TraitRef<'tcx>,
582     trait_assoc_def_id: DefId,
583     impl_def_id: DefId,
584 ) -> Result<Option<LeafDef>, NoSolution> {
585     let node_item = specialization_graph::assoc_def(infcx.tcx, impl_def_id, trait_assoc_def_id)
586         .map_err(|ErrorGuaranteed { .. }| NoSolution)?;
587
588     let eligible = if node_item.is_final() {
589         // Non-specializable items are always projectable.
590         true
591     } else {
592         // Only reveal a specializable default if we're past type-checking
593         // and the obligation is monomorphic, otherwise passes such as
594         // transmute checking and polymorphic MIR optimizations could
595         // get a result which isn't correct for all monomorphizations.
596         if param_env.reveal() == Reveal::All {
597             let poly_trait_ref = infcx.resolve_vars_if_possible(goal_trait_ref);
598             !poly_trait_ref.still_further_specializable()
599         } else {
600             debug!(?node_item.item.def_id, "not eligible due to default");
601             false
602         }
603     };
604
605     if eligible { Ok(Some(node_item)) } else { Ok(None) }
606 }