1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
9 pub mod const_evaluatable;
11 pub mod error_reporting;
18 pub(crate) mod relationships;
25 use crate::infer::outlives::env::OutlivesEnvironment;
26 use crate::infer::{InferCtxt, TyCtxtInferExt};
27 use crate::traits::error_reporting::InferCtxtExt as _;
28 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
29 use rustc_errors::ErrorGuaranteed;
31 use rustc_hir::def_id::DefId;
32 use rustc_hir::lang_items::LangItem;
33 use rustc_infer::traits::TraitEngineExt as _;
34 use rustc_middle::ty::fold::TypeFoldable;
35 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
36 use rustc_middle::ty::visit::TypeVisitable;
37 use rustc_middle::ty::{
38 self, DefIdTree, GenericParamDefKind, Subst, ToPredicate, Ty, TyCtxt, TypeSuperVisitable,
41 use rustc_span::{sym, Span};
42 use smallvec::SmallVec;
45 use std::ops::ControlFlow;
47 pub use self::FulfillmentErrorCode::*;
48 pub use self::ImplSource::*;
49 pub use self::ObligationCauseCode::*;
50 pub use self::SelectionError::*;
52 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
53 pub use self::coherence::{OrphanCheckErr, OverlapResult};
54 pub use self::engine::{ObligationCtxt, TraitEngineExt};
55 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
56 pub use self::object_safety::astconv_object_safety_violations;
57 pub use self::object_safety::is_vtable_safe_method;
58 pub use self::object_safety::MethodViolationCode;
59 pub use self::object_safety::ObjectSafetyViolation;
60 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
61 pub use self::project::{normalize, normalize_projection_type, normalize_to};
62 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
63 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
64 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
65 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
66 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
67 pub use self::structural_match::{
68 search_for_adt_const_param_violation, search_for_structural_match_violation,
71 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
72 elaborate_trait_ref, elaborate_trait_refs,
74 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
76 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
79 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
80 SupertraitDefIds, Supertraits,
83 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
85 pub use rustc_infer::traits::*;
87 /// Whether to skip the leak check, as part of a future compatibility warning step.
89 /// The "default" for skip-leak-check corresponds to the current
90 /// behavior (do not skip the leak check) -- not the behavior we are
91 /// transitioning into.
92 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
93 pub enum SkipLeakCheck {
100 fn is_yes(self) -> bool {
101 self == SkipLeakCheck::Yes
105 /// The mode that trait queries run in.
106 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
107 pub enum TraitQueryMode {
108 /// Standard/un-canonicalized queries get accurate
109 /// spans etc. passed in and hence can do reasonable
110 /// error reporting on their own.
112 /// Canonicalized queries get dummy spans and hence
113 /// must generally propagate errors to
114 /// pre-canonicalization callsites.
118 /// Creates predicate obligations from the generic bounds.
119 pub fn predicates_for_generics<'tcx>(
120 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
121 param_env: ty::ParamEnv<'tcx>,
122 generic_bounds: ty::InstantiatedPredicates<'tcx>,
123 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
124 let generic_bounds = generic_bounds;
125 debug!("predicates_for_generics(generic_bounds={:?})", generic_bounds);
127 std::iter::zip(generic_bounds.predicates, generic_bounds.spans).enumerate().map(
128 move |(idx, (predicate, span))| Obligation {
129 cause: cause(idx, span),
131 param_env: param_env,
137 /// Determines whether the type `ty` is known to meet `bound` and
138 /// returns true if so. Returns false if `ty` either does not meet
139 /// `bound` or is not known to meet bound (note that this is
140 /// conservative towards *no impl*, which is the opposite of the
141 /// `evaluate` methods).
142 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
143 infcx: &InferCtxt<'a, 'tcx>,
144 param_env: ty::ParamEnv<'tcx>,
150 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
152 infcx.tcx.def_path_str(def_id)
156 ty::Binder::dummy(ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) });
157 let obligation = Obligation {
159 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
161 predicate: trait_ref.without_const().to_predicate(infcx.tcx),
164 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
166 "type_known_to_meet_ty={:?} bound={} => {:?}",
168 infcx.tcx.def_path_str(def_id),
172 if result && ty.has_infer_types_or_consts() {
173 // Because of inference "guessing", selection can sometimes claim
174 // to succeed while the success requires a guess. To ensure
175 // this function's result remains infallible, we must confirm
176 // that guess. While imperfect, I believe this is sound.
178 // We can use a dummy node-id here because we won't pay any mind
179 // to region obligations that arise (there shouldn't really be any
181 let cause = ObligationCause::misc(span, hir::CRATE_HIR_ID);
183 // The handling of regions in this area of the code is terrible,
184 // see issue #29149. We should be able to improve on this with
186 let errors = fully_solve_bound(infcx, cause, param_env, ty, def_id);
188 // Note: we only assume something is `Copy` if we can
189 // *definitively* show that it implements `Copy`. Otherwise,
190 // assume it is move; linear is always ok.
194 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
196 infcx.tcx.def_path_str(def_id)
203 bound = %infcx.tcx.def_path_str(def_id),
205 "type_known_to_meet_bound_modulo_regions"
215 #[instrument(level = "debug", skip(tcx, elaborated_env))]
216 fn do_normalize_predicates<'tcx>(
218 cause: ObligationCause<'tcx>,
219 elaborated_env: ty::ParamEnv<'tcx>,
220 predicates: Vec<ty::Predicate<'tcx>>,
221 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
222 let span = cause.span;
223 // FIXME. We should really... do something with these region
224 // obligations. But this call just continues the older
225 // behavior (i.e., doesn't cause any new bugs), and it would
226 // take some further refactoring to actually solve them. In
227 // particular, we would have to handle implied bounds
228 // properly, and that code is currently largely confined to
229 // regionck (though I made some efforts to extract it
232 // @arielby: In any case, these obligations are checked
233 // by wfcheck anyway, so I'm not sure we have to check
234 // them here too, and we will remove this function when
235 // we move over to lazy normalization *anyway*.
236 tcx.infer_ctxt().ignoring_regions().enter(|infcx| {
237 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
238 Ok(predicates) => predicates,
240 let reported = infcx.report_fulfillment_errors(&errors, None, false);
241 return Err(reported);
245 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
247 // We can use the `elaborated_env` here; the region code only
248 // cares about declarations like `'a: 'b`.
249 let outlives_env = OutlivesEnvironment::new(elaborated_env);
251 // FIXME: It's very weird that we ignore region obligations but apparently
252 // still need to use `resolve_regions` as we need the resolved regions in
253 // the normalized predicates.
254 let errors = infcx.resolve_regions(&outlives_env);
255 if !errors.is_empty() {
256 tcx.sess.delay_span_bug(
259 "failed region resolution while normalizing {elaborated_env:?}: {errors:?}"
264 match infcx.fully_resolve(predicates) {
265 Ok(predicates) => Ok(predicates),
267 // If we encounter a fixup error, it means that some type
268 // variable wound up unconstrained. I actually don't know
269 // if this can happen, and I certainly don't expect it to
270 // happen often, but if it did happen it probably
271 // represents a legitimate failure due to some kind of
272 // unconstrained variable.
274 // @lcnr: Let's still ICE here for now. I want a test case
278 "inference variables in normalized parameter environment: {}",
286 // FIXME: this is gonna need to be removed ...
287 /// Normalizes the parameter environment, reporting errors if they occur.
288 #[instrument(level = "debug", skip(tcx))]
289 pub fn normalize_param_env_or_error<'tcx>(
291 unnormalized_env: ty::ParamEnv<'tcx>,
292 cause: ObligationCause<'tcx>,
293 ) -> ty::ParamEnv<'tcx> {
294 // I'm not wild about reporting errors here; I'd prefer to
295 // have the errors get reported at a defined place (e.g.,
296 // during typeck). Instead I have all parameter
297 // environments, in effect, going through this function
298 // and hence potentially reporting errors. This ensures of
299 // course that we never forget to normalize (the
300 // alternative seemed like it would involve a lot of
301 // manual invocations of this fn -- and then we'd have to
302 // deal with the errors at each of those sites).
304 // In any case, in practice, typeck constructs all the
305 // parameter environments once for every fn as it goes,
306 // and errors will get reported then; so outside of type inference we
307 // can be sure that no errors should occur.
308 let mut predicates: Vec<_> =
309 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
310 .map(|obligation| obligation.predicate)
313 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
315 let elaborated_env = ty::ParamEnv::new(
316 tcx.intern_predicates(&predicates),
317 unnormalized_env.reveal(),
318 unnormalized_env.constness(),
321 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
322 // normalization expects its param-env to be already normalized, which means we have
325 // The way we handle this is by normalizing the param-env inside an unnormalized version
326 // of the param-env, which means that if the param-env contains unnormalized projections,
327 // we'll have some normalization failures. This is unfortunate.
329 // Lazy normalization would basically handle this by treating just the
330 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
332 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
333 // types, so to make the situation less bad, we normalize all the predicates *but*
334 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
335 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
337 // This works fairly well because trait matching does not actually care about param-env
338 // TypeOutlives predicates - these are normally used by regionck.
339 let outlives_predicates: Vec<_> = predicates
340 .drain_filter(|predicate| {
341 matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..))
346 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
347 predicates, outlives_predicates
349 let Ok(non_outlives_predicates) = do_normalize_predicates(
355 // An unnormalized env is better than nothing.
356 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
357 return elaborated_env;
360 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
362 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
363 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
364 // predicates here anyway. Keeping them here anyway because it seems safer.
365 let outlives_env: Vec<_> =
366 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
367 let outlives_env = ty::ParamEnv::new(
368 tcx.intern_predicates(&outlives_env),
369 unnormalized_env.reveal(),
370 unnormalized_env.constness(),
372 let Ok(outlives_predicates) = do_normalize_predicates(
378 // An unnormalized env is better than nothing.
379 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
380 return elaborated_env;
382 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
384 let mut predicates = non_outlives_predicates;
385 predicates.extend(outlives_predicates);
386 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
388 tcx.intern_predicates(&predicates),
389 unnormalized_env.reveal(),
390 unnormalized_env.constness(),
394 /// Normalize a type and process all resulting obligations, returning any errors
395 pub fn fully_normalize<'a, 'tcx, T>(
396 infcx: &InferCtxt<'a, 'tcx>,
397 cause: ObligationCause<'tcx>,
398 param_env: ty::ParamEnv<'tcx>,
400 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
402 T: TypeFoldable<'tcx>,
404 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
405 let selcx = &mut SelectionContext::new(infcx);
406 let Normalized { value: normalized_value, obligations } =
407 project::normalize(selcx, param_env, cause, value);
409 "fully_normalize: normalized_value={:?} obligations={:?}",
410 normalized_value, obligations
413 let mut fulfill_cx = FulfillmentContext::new();
414 for obligation in obligations {
415 fulfill_cx.register_predicate_obligation(infcx, obligation);
418 debug!("fully_normalize: select_all_or_error start");
419 let errors = fulfill_cx.select_all_or_error(infcx);
420 if !errors.is_empty() {
423 debug!("fully_normalize: select_all_or_error complete");
424 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
425 debug!("fully_normalize: resolved_value={:?}", resolved_value);
429 /// Process an obligation (and any nested obligations that come from it) to
430 /// completion, returning any errors
431 pub fn fully_solve_obligation<'a, 'tcx>(
432 infcx: &InferCtxt<'a, 'tcx>,
433 obligation: PredicateObligation<'tcx>,
434 ) -> Vec<FulfillmentError<'tcx>> {
435 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
436 engine.register_predicate_obligation(infcx, obligation);
437 engine.select_all_or_error(infcx)
440 /// Process a set of obligations (and any nested obligations that come from them)
442 pub fn fully_solve_obligations<'a, 'tcx>(
443 infcx: &InferCtxt<'a, 'tcx>,
444 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
445 ) -> Vec<FulfillmentError<'tcx>> {
446 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
447 engine.register_predicate_obligations(infcx, obligations);
448 engine.select_all_or_error(infcx)
451 /// Process a bound (and any nested obligations that come from it) to completion.
452 /// This is a convenience function for traits that have no generic arguments, such
453 /// as auto traits, and builtin traits like Copy or Sized.
454 pub fn fully_solve_bound<'a, 'tcx>(
455 infcx: &InferCtxt<'a, 'tcx>,
456 cause: ObligationCause<'tcx>,
457 param_env: ty::ParamEnv<'tcx>,
460 ) -> Vec<FulfillmentError<'tcx>> {
461 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
462 engine.register_bound(infcx, param_env, ty, bound, cause);
463 engine.select_all_or_error(infcx)
466 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
467 /// returns true, then either normalize encountered an error or one of the predicates did not
468 /// hold. Used when creating vtables to check for unsatisfiable methods.
469 pub fn impossible_predicates<'tcx>(
471 predicates: Vec<ty::Predicate<'tcx>>,
473 debug!("impossible_predicates(predicates={:?})", predicates);
475 let result = tcx.infer_ctxt().enter(|infcx| {
476 // HACK: Set tainted by errors to gracefully exit in case of overflow.
477 infcx.set_tainted_by_errors();
479 let param_env = ty::ParamEnv::reveal_all();
480 let ocx = ObligationCtxt::new(&infcx);
481 let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);
482 for predicate in predicates {
483 let obligation = Obligation::new(ObligationCause::dummy(), param_env, predicate);
484 ocx.register_obligation(obligation);
486 let errors = ocx.select_all_or_error();
488 // Clean up after ourselves
489 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
493 debug!("impossible_predicates = {:?}", result);
497 fn subst_and_check_impossible_predicates<'tcx>(
499 key: (DefId, SubstsRef<'tcx>),
501 debug!("subst_and_check_impossible_predicates(key={:?})", key);
503 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
505 // Specifically check trait fulfillment to avoid an error when trying to resolve
507 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
508 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
509 predicates.push(ty::Binder::dummy(trait_ref).to_poly_trait_predicate().to_predicate(tcx));
512 predicates.retain(|predicate| !predicate.needs_subst());
513 let result = impossible_predicates(tcx, predicates);
515 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
519 /// Checks whether a trait's method is impossible to call on a given impl.
521 /// This only considers predicates that reference the impl's generics, and not
522 /// those that reference the method's generics.
523 fn is_impossible_method<'tcx>(
525 (impl_def_id, trait_item_def_id): (DefId, DefId),
527 struct ReferencesOnlyParentGenerics<'tcx> {
529 generics: &'tcx ty::Generics,
530 trait_item_def_id: DefId,
532 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
534 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
535 // If this is a parameter from the trait item's own generics, then bail
536 if let ty::Param(param) = t.kind()
537 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
538 && self.tcx.parent(param_def_id) == self.trait_item_def_id
540 return ControlFlow::BREAK;
542 t.super_visit_with(self)
544 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
545 if let ty::ReEarlyBound(param) = r.kind()
546 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
547 && self.tcx.parent(param_def_id) == self.trait_item_def_id
549 return ControlFlow::BREAK;
551 r.super_visit_with(self)
553 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
554 if let ty::ConstKind::Param(param) = ct.kind()
555 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
556 && self.tcx.parent(param_def_id) == self.trait_item_def_id
558 return ControlFlow::BREAK;
560 ct.super_visit_with(self)
564 let generics = tcx.generics_of(trait_item_def_id);
565 let predicates = tcx.predicates_of(trait_item_def_id);
567 tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
568 let param_env = tcx.param_env(impl_def_id);
570 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
571 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
572 if pred.visit_with(&mut visitor).is_continue() {
573 Some(Obligation::new(
574 ObligationCause::dummy_with_span(*span),
576 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
583 tcx.infer_ctxt().ignoring_regions().enter(|ref infcx| {
584 let mut fulfill_ctxt = <dyn TraitEngine<'_>>::new(tcx);
585 fulfill_ctxt.register_predicate_obligations(infcx, predicates_for_trait);
586 !fulfill_ctxt.select_all_or_error(infcx).is_empty()
590 #[derive(Clone, Debug)]
591 enum VtblSegment<'tcx> {
593 TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
596 /// Prepare the segments for a vtable
597 fn prepare_vtable_segments<'tcx, T>(
599 trait_ref: ty::PolyTraitRef<'tcx>,
600 mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
602 // The following constraints holds for the final arrangement.
603 // 1. The whole virtual table of the first direct super trait is included as the
604 // the prefix. If this trait doesn't have any super traits, then this step
605 // consists of the dsa metadata.
606 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
607 // other super traits except those already included as part of the first
608 // direct super trait virtual table.
609 // 3. finally, the own methods of this trait.
611 // This has the advantage that trait upcasting to the first direct super trait on each level
612 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
613 // while not using too much extra memory.
615 // For a single inheritance relationship like this,
616 // D --> C --> B --> A
617 // The resulting vtable will consists of these segments:
620 // For a multiple inheritance relationship like this,
623 // The resulting vtable will consists of these segments:
624 // DSA, A, B, B-vptr, C, D
626 // For a diamond inheritance relationship like this,
629 // The resulting vtable will consists of these segments:
630 // DSA, A, B, C, C-vptr, D
632 // For a more complex inheritance relationship like this:
633 // O --> G --> C --> A
641 // The resulting vtable will consists of these segments:
642 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
643 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
646 // emit dsa segment first.
647 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
651 let mut emit_vptr_on_new_entry = false;
652 let mut visited = util::PredicateSet::new(tcx);
653 let predicate = trait_ref.without_const().to_predicate(tcx);
654 let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
655 smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
656 visited.insert(predicate);
658 // the main traversal loop:
659 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
660 // that each node is emitted after all its descendents have been emitted.
661 // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
662 // this is done on the fly.
663 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
664 // stops after it finds a node that has a next-sibling node.
665 // This next-sibling node will used as the starting point of next slice.
668 // For a diamond inheritance relationship like this,
669 // D#1 --> B#0 --> A#0
672 // Starting point 0 stack [D]
673 // Loop run #0: Stack after diving in is [D B A], A is "childless"
674 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
675 // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
676 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
677 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
678 // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
679 // Loop run #1: Stack after exiting out is []. Now the function exits.
682 // dive deeper into the stack, recording the path
684 if let Some((inner_most_trait_ref, _, _)) = stack.last() {
685 let inner_most_trait_ref = *inner_most_trait_ref;
686 let mut direct_super_traits_iter = tcx
687 .super_predicates_of(inner_most_trait_ref.def_id())
690 .filter_map(move |(pred, _)| {
691 pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
694 'diving_in_skip_visited_traits: loop {
695 if let Some(next_super_trait) = direct_super_traits_iter.next() {
696 if visited.insert(next_super_trait.to_predicate(tcx)) {
697 // We're throwing away potential constness of super traits here.
698 // FIXME: handle ~const super traits
699 let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
702 emit_vptr_on_new_entry,
703 Some(direct_super_traits_iter),
705 break 'diving_in_skip_visited_traits;
707 continue 'diving_in_skip_visited_traits;
716 // Other than the left-most path, vptr should be emitted for each trait.
717 emit_vptr_on_new_entry = true;
719 // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
721 if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
722 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
723 trait_ref: *inner_most_trait_ref,
724 emit_vptr: *emit_vptr,
729 'exiting_out_skip_visited_traits: loop {
730 if let Some(siblings) = siblings_opt {
731 if let Some(next_inner_most_trait_ref) = siblings.next() {
732 if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
733 // We're throwing away potential constness of super traits here.
734 // FIXME: handle ~const super traits
735 let next_inner_most_trait_ref =
736 next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
737 *inner_most_trait_ref = next_inner_most_trait_ref;
738 *emit_vptr = emit_vptr_on_new_entry;
741 continue 'exiting_out_skip_visited_traits;
746 continue 'exiting_out;
755 fn dump_vtable_entries<'tcx>(
758 trait_ref: ty::PolyTraitRef<'tcx>,
759 entries: &[VtblEntry<'tcx>],
761 let msg = format!("vtable entries for `{}`: {:#?}", trait_ref, entries);
762 tcx.sess.struct_span_err(sp, &msg).emit();
765 fn own_existential_vtable_entries<'tcx>(
767 trait_ref: ty::PolyExistentialTraitRef<'tcx>,
769 let trait_methods = tcx
770 .associated_items(trait_ref.def_id())
771 .in_definition_order()
772 .filter(|item| item.kind == ty::AssocKind::Fn);
773 // Now list each method's DefId (for within its trait).
774 let own_entries = trait_methods.filter_map(move |trait_method| {
775 debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
776 let def_id = trait_method.def_id;
778 // Some methods cannot be called on an object; skip those.
779 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
780 debug!("own_existential_vtable_entry: not vtable safe");
787 tcx.arena.alloc_from_iter(own_entries.into_iter())
790 /// Given a trait `trait_ref`, iterates the vtable entries
791 /// that come from `trait_ref`, including its supertraits.
792 fn vtable_entries<'tcx>(
794 trait_ref: ty::PolyTraitRef<'tcx>,
795 ) -> &'tcx [VtblEntry<'tcx>] {
796 debug!("vtable_entries({:?})", trait_ref);
798 let mut entries = vec![];
800 let vtable_segment_callback = |segment| -> ControlFlow<()> {
802 VtblSegment::MetadataDSA => {
803 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
805 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
806 let existential_trait_ref = trait_ref
807 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
809 // Lookup the shape of vtable for the trait.
810 let own_existential_entries =
811 tcx.own_existential_vtable_entries(existential_trait_ref);
813 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
814 debug!("vtable_entries: trait_method={:?}", def_id);
816 // The method may have some early-bound lifetimes; add regions for those.
817 let substs = trait_ref.map_bound(|trait_ref| {
818 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
819 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
820 GenericParamDefKind::Type { .. }
821 | GenericParamDefKind::Const { .. } => {
822 trait_ref.substs[param.index as usize]
827 // The trait type may have higher-ranked lifetimes in it;
828 // erase them if they appear, so that we get the type
829 // at some particular call site.
831 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
833 // It's possible that the method relies on where-clauses that
834 // do not hold for this particular set of type parameters.
835 // Note that this method could then never be called, so we
836 // do not want to try and codegen it, in that case (see #23435).
837 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
838 if impossible_predicates(tcx, predicates.predicates) {
839 debug!("vtable_entries: predicates do not hold");
840 return VtblEntry::Vacant;
843 let instance = ty::Instance::resolve_for_vtable(
845 ty::ParamEnv::reveal_all(),
849 .expect("resolution failed during building vtable representation");
850 VtblEntry::Method(instance)
853 entries.extend(own_entries);
856 entries.push(VtblEntry::TraitVPtr(trait_ref));
861 ControlFlow::Continue(())
864 let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
866 if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
867 let sp = tcx.def_span(trait_ref.def_id());
868 dump_vtable_entries(tcx, sp, trait_ref, &entries);
871 tcx.arena.alloc_from_iter(entries.into_iter())
874 /// Find slot base for trait methods within vtable entries of another trait
875 fn vtable_trait_first_method_offset<'tcx>(
878 ty::PolyTraitRef<'tcx>, // trait_to_be_found
879 ty::PolyTraitRef<'tcx>, // trait_owning_vtable
882 let (trait_to_be_found, trait_owning_vtable) = key;
885 let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
887 let vtable_segment_callback = {
888 let mut vtable_base = 0;
892 VtblSegment::MetadataDSA => {
893 vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
895 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
896 if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
897 return ControlFlow::Break(vtable_base);
899 vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
905 ControlFlow::Continue(())
909 if let Some(vtable_base) =
910 prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
914 bug!("Failed to find info for expected trait in vtable");
918 /// Find slot offset for trait vptr within vtable entries of another trait
919 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
922 Ty<'tcx>, // trait object type whose trait owning vtable
923 Ty<'tcx>, // trait object for supertrait
926 let (source, target) = key;
927 assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
928 assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
930 // this has been typecked-before, so diagnostics is not really needed.
931 let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
933 let trait_ref = ty::TraitRef {
934 def_id: unsize_trait_did,
935 substs: tcx.mk_substs_trait(source, &[target.into()]),
937 let obligation = Obligation::new(
938 ObligationCause::dummy(),
939 ty::ParamEnv::reveal_all(),
940 ty::Binder::dummy(ty::TraitPredicate {
942 constness: ty::BoundConstness::NotConst,
943 polarity: ty::ImplPolarity::Positive,
947 let implsrc = tcx.infer_ctxt().enter(|infcx| {
948 let mut selcx = SelectionContext::new(&infcx);
949 selcx.select(&obligation).unwrap()
952 let Some(ImplSource::TraitUpcasting(implsrc_traitcasting)) = implsrc else {
956 implsrc_traitcasting.vtable_vptr_slot
959 pub fn provide(providers: &mut ty::query::Providers) {
960 object_safety::provide(providers);
961 structural_match::provide(providers);
962 *providers = ty::query::Providers {
963 specialization_graph_of: specialize::specialization_graph_provider,
964 specializes: specialize::specializes,
965 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
966 own_existential_vtable_entries,
968 vtable_trait_upcasting_coercion_new_vptr_slot,
969 subst_and_check_impossible_predicates,
970 is_impossible_method,
971 try_unify_abstract_consts: |tcx, param_env_and| {
972 let (param_env, (a, b)) = param_env_and.into_parts();
973 const_evaluatable::try_unify_abstract_consts(tcx, (a, b), param_env)