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;
16 pub mod outlives_bounds;
19 pub(crate) mod relationships;
26 use crate::errors::DumpVTableEntries;
27 use crate::infer::outlives::env::OutlivesEnvironment;
28 use crate::infer::{InferCtxt, TyCtxtInferExt};
29 use crate::traits::error_reporting::InferCtxtExt as _;
30 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
31 use rustc_errors::ErrorGuaranteed;
33 use rustc_hir::def_id::DefId;
34 use rustc_hir::lang_items::LangItem;
35 use rustc_infer::traits::TraitEngineExt as _;
36 use rustc_middle::ty::fold::TypeFoldable;
37 use rustc_middle::ty::visit::TypeVisitable;
38 use rustc_middle::ty::{
39 self, DefIdTree, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeSuperVisitable, VtblEntry,
41 use rustc_middle::ty::{InternalSubsts, SubstsRef};
42 use rustc_span::{sym, Span};
43 use smallvec::SmallVec;
46 use std::ops::ControlFlow;
48 pub use self::FulfillmentErrorCode::*;
49 pub use self::ImplSource::*;
50 pub use self::ObligationCauseCode::*;
51 pub use self::SelectionError::*;
53 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
54 pub use self::coherence::{OrphanCheckErr, OverlapResult};
55 pub use self::engine::{ObligationCtxt, TraitEngineExt};
56 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
57 pub use self::object_safety::astconv_object_safety_violations;
58 pub use self::object_safety::is_vtable_safe_method;
59 pub use self::object_safety::MethodViolationCode;
60 pub use self::object_safety::ObjectSafetyViolation;
61 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
62 pub use self::project::{normalize, normalize_projection_type, normalize_to};
63 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
64 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
65 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
66 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
67 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
68 pub use self::structural_match::{
69 search_for_adt_const_param_violation, search_for_structural_match_violation,
72 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
73 elaborate_trait_ref, elaborate_trait_refs,
75 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
77 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
80 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
81 SupertraitDefIds, Supertraits,
84 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
86 pub use rustc_infer::traits::*;
88 /// Whether to skip the leak check, as part of a future compatibility warning step.
90 /// The "default" for skip-leak-check corresponds to the current
91 /// behavior (do not skip the leak check) -- not the behavior we are
92 /// transitioning into.
93 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
94 pub enum SkipLeakCheck {
101 fn is_yes(self) -> bool {
102 self == SkipLeakCheck::Yes
106 /// The mode that trait queries run in.
107 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
108 pub enum TraitQueryMode {
109 /// Standard/un-canonicalized queries get accurate
110 /// spans etc. passed in and hence can do reasonable
111 /// error reporting on their own.
113 /// Canonicalized queries get dummy spans and hence
114 /// must generally propagate errors to
115 /// pre-canonicalization callsites.
119 /// Creates predicate obligations from the generic bounds.
120 pub fn predicates_for_generics<'tcx>(
121 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
122 param_env: ty::ParamEnv<'tcx>,
123 generic_bounds: ty::InstantiatedPredicates<'tcx>,
124 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
125 let generic_bounds = generic_bounds;
126 debug!("predicates_for_generics(generic_bounds={:?})", generic_bounds);
128 std::iter::zip(generic_bounds.predicates, generic_bounds.spans).enumerate().map(
129 move |(idx, (predicate, span))| Obligation {
130 cause: cause(idx, span),
138 /// Determines whether the type `ty` is known to meet `bound` and
139 /// returns true if so. Returns false if `ty` either does not meet
140 /// `bound` or is not known to meet bound (note that this is
141 /// conservative towards *no impl*, which is the opposite of the
142 /// `evaluate` methods).
143 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
144 infcx: &InferCtxt<'a, 'tcx>,
145 param_env: ty::ParamEnv<'tcx>,
151 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
153 infcx.tcx.def_path_str(def_id)
157 ty::Binder::dummy(ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) });
158 let obligation = Obligation {
160 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
162 predicate: trait_ref.without_const().to_predicate(infcx.tcx),
165 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
167 "type_known_to_meet_ty={:?} bound={} => {:?}",
169 infcx.tcx.def_path_str(def_id),
173 if result && ty.has_infer_types_or_consts() {
174 // Because of inference "guessing", selection can sometimes claim
175 // to succeed while the success requires a guess. To ensure
176 // this function's result remains infallible, we must confirm
177 // that guess. While imperfect, I believe this is sound.
179 // We can use a dummy node-id here because we won't pay any mind
180 // to region obligations that arise (there shouldn't really be any
182 let cause = ObligationCause::misc(span, hir::CRATE_HIR_ID);
184 // The handling of regions in this area of the code is terrible,
185 // see issue #29149. We should be able to improve on this with
187 let errors = fully_solve_bound(infcx, cause, param_env, ty, def_id);
189 // Note: we only assume something is `Copy` if we can
190 // *definitively* show that it implements `Copy`. Otherwise,
191 // assume it is move; linear is always ok.
195 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
197 infcx.tcx.def_path_str(def_id)
204 bound = %infcx.tcx.def_path_str(def_id),
206 "type_known_to_meet_bound_modulo_regions"
216 #[instrument(level = "debug", skip(tcx, elaborated_env))]
217 fn do_normalize_predicates<'tcx>(
219 cause: ObligationCause<'tcx>,
220 elaborated_env: ty::ParamEnv<'tcx>,
221 predicates: Vec<ty::Predicate<'tcx>>,
222 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
223 let span = cause.span;
224 // FIXME. We should really... do something with these region
225 // obligations. But this call just continues the older
226 // behavior (i.e., doesn't cause any new bugs), and it would
227 // take some further refactoring to actually solve them. In
228 // particular, we would have to handle implied bounds
229 // properly, and that code is currently largely confined to
230 // regionck (though I made some efforts to extract it
233 // @arielby: In any case, these obligations are checked
234 // by wfcheck anyway, so I'm not sure we have to check
235 // them here too, and we will remove this function when
236 // we move over to lazy normalization *anyway*.
237 tcx.infer_ctxt().ignoring_regions().enter(|infcx| {
238 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
239 Ok(predicates) => predicates,
241 let reported = infcx.report_fulfillment_errors(&errors, None, false);
242 return Err(reported);
246 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
248 // We can use the `elaborated_env` here; the region code only
249 // cares about declarations like `'a: 'b`.
250 let outlives_env = OutlivesEnvironment::new(elaborated_env);
252 // FIXME: It's very weird that we ignore region obligations but apparently
253 // still need to use `resolve_regions` as we need the resolved regions in
254 // the normalized predicates.
255 let errors = infcx.resolve_regions(&outlives_env);
256 if !errors.is_empty() {
257 tcx.sess.delay_span_bug(
260 "failed region resolution while normalizing {elaborated_env:?}: {errors:?}"
265 match infcx.fully_resolve(predicates) {
266 Ok(predicates) => Ok(predicates),
268 // If we encounter a fixup error, it means that some type
269 // variable wound up unconstrained. I actually don't know
270 // if this can happen, and I certainly don't expect it to
271 // happen often, but if it did happen it probably
272 // represents a legitimate failure due to some kind of
273 // unconstrained variable.
275 // @lcnr: Let's still ICE here for now. I want a test case
279 "inference variables in normalized parameter environment: {}",
287 // FIXME: this is gonna need to be removed ...
288 /// Normalizes the parameter environment, reporting errors if they occur.
289 #[instrument(level = "debug", skip(tcx))]
290 pub fn normalize_param_env_or_error<'tcx>(
292 unnormalized_env: ty::ParamEnv<'tcx>,
293 cause: ObligationCause<'tcx>,
294 ) -> ty::ParamEnv<'tcx> {
295 // I'm not wild about reporting errors here; I'd prefer to
296 // have the errors get reported at a defined place (e.g.,
297 // during typeck). Instead I have all parameter
298 // environments, in effect, going through this function
299 // and hence potentially reporting errors. This ensures of
300 // course that we never forget to normalize (the
301 // alternative seemed like it would involve a lot of
302 // manual invocations of this fn -- and then we'd have to
303 // deal with the errors at each of those sites).
305 // In any case, in practice, typeck constructs all the
306 // parameter environments once for every fn as it goes,
307 // and errors will get reported then; so outside of type inference we
308 // can be sure that no errors should occur.
309 let mut predicates: Vec<_> =
310 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
311 .map(|obligation| obligation.predicate)
314 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
316 let elaborated_env = ty::ParamEnv::new(
317 tcx.intern_predicates(&predicates),
318 unnormalized_env.reveal(),
319 unnormalized_env.constness(),
322 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
323 // normalization expects its param-env to be already normalized, which means we have
326 // The way we handle this is by normalizing the param-env inside an unnormalized version
327 // of the param-env, which means that if the param-env contains unnormalized projections,
328 // we'll have some normalization failures. This is unfortunate.
330 // Lazy normalization would basically handle this by treating just the
331 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
333 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
334 // types, so to make the situation less bad, we normalize all the predicates *but*
335 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
336 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
338 // This works fairly well because trait matching does not actually care about param-env
339 // TypeOutlives predicates - these are normally used by regionck.
340 let outlives_predicates: Vec<_> = predicates
341 .drain_filter(|predicate| {
342 matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..))
347 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
348 predicates, outlives_predicates
350 let Ok(non_outlives_predicates) = do_normalize_predicates(
356 // An unnormalized env is better than nothing.
357 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
358 return elaborated_env;
361 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
363 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
364 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
365 // predicates here anyway. Keeping them here anyway because it seems safer.
366 let outlives_env: Vec<_> =
367 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
368 let outlives_env = ty::ParamEnv::new(
369 tcx.intern_predicates(&outlives_env),
370 unnormalized_env.reveal(),
371 unnormalized_env.constness(),
373 let Ok(outlives_predicates) = do_normalize_predicates(
379 // An unnormalized env is better than nothing.
380 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
381 return elaborated_env;
383 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
385 let mut predicates = non_outlives_predicates;
386 predicates.extend(outlives_predicates);
387 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
389 tcx.intern_predicates(&predicates),
390 unnormalized_env.reveal(),
391 unnormalized_env.constness(),
395 /// Normalize a type and process all resulting obligations, returning any errors
396 pub fn fully_normalize<'a, 'tcx, T>(
397 infcx: &InferCtxt<'a, 'tcx>,
398 cause: ObligationCause<'tcx>,
399 param_env: ty::ParamEnv<'tcx>,
401 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
403 T: TypeFoldable<'tcx>,
405 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
406 let selcx = &mut SelectionContext::new(infcx);
407 let Normalized { value: normalized_value, obligations } =
408 project::normalize(selcx, param_env, cause, value);
410 "fully_normalize: normalized_value={:?} obligations={:?}",
411 normalized_value, obligations
414 let mut fulfill_cx = FulfillmentContext::new();
415 for obligation in obligations {
416 fulfill_cx.register_predicate_obligation(infcx, obligation);
419 debug!("fully_normalize: select_all_or_error start");
420 let errors = fulfill_cx.select_all_or_error(infcx);
421 if !errors.is_empty() {
424 debug!("fully_normalize: select_all_or_error complete");
425 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
426 debug!("fully_normalize: resolved_value={:?}", resolved_value);
430 /// Process an obligation (and any nested obligations that come from it) to
431 /// completion, returning any errors
432 pub fn fully_solve_obligation<'a, 'tcx>(
433 infcx: &InferCtxt<'a, 'tcx>,
434 obligation: PredicateObligation<'tcx>,
435 ) -> Vec<FulfillmentError<'tcx>> {
436 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
437 engine.register_predicate_obligation(infcx, obligation);
438 engine.select_all_or_error(infcx)
441 /// Process a set of obligations (and any nested obligations that come from them)
443 pub fn fully_solve_obligations<'a, 'tcx>(
444 infcx: &InferCtxt<'a, 'tcx>,
445 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
446 ) -> Vec<FulfillmentError<'tcx>> {
447 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
448 engine.register_predicate_obligations(infcx, obligations);
449 engine.select_all_or_error(infcx)
452 /// Process a bound (and any nested obligations that come from it) to completion.
453 /// This is a convenience function for traits that have no generic arguments, such
454 /// as auto traits, and builtin traits like Copy or Sized.
455 pub fn fully_solve_bound<'a, 'tcx>(
456 infcx: &InferCtxt<'a, 'tcx>,
457 cause: ObligationCause<'tcx>,
458 param_env: ty::ParamEnv<'tcx>,
461 ) -> Vec<FulfillmentError<'tcx>> {
462 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
463 engine.register_bound(infcx, param_env, ty, bound, cause);
464 engine.select_all_or_error(infcx)
467 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
468 /// returns true, then either normalize encountered an error or one of the predicates did not
469 /// hold. Used when creating vtables to check for unsatisfiable methods.
470 pub fn impossible_predicates<'tcx>(
472 predicates: Vec<ty::Predicate<'tcx>>,
474 debug!("impossible_predicates(predicates={:?})", predicates);
476 let result = tcx.infer_ctxt().enter(|infcx| {
477 let param_env = ty::ParamEnv::reveal_all();
478 let ocx = ObligationCtxt::new(&infcx);
479 let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);
480 for predicate in predicates {
481 let obligation = Obligation::new(ObligationCause::dummy(), param_env, predicate);
482 ocx.register_obligation(obligation);
484 let errors = ocx.select_all_or_error();
486 // Clean up after ourselves
487 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
491 debug!("impossible_predicates = {:?}", result);
495 fn subst_and_check_impossible_predicates<'tcx>(
497 key: (DefId, SubstsRef<'tcx>),
499 debug!("subst_and_check_impossible_predicates(key={:?})", key);
501 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
503 // Specifically check trait fulfillment to avoid an error when trying to resolve
505 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
506 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
507 predicates.push(ty::Binder::dummy(trait_ref).to_poly_trait_predicate().to_predicate(tcx));
510 predicates.retain(|predicate| !predicate.needs_subst());
511 let result = impossible_predicates(tcx, predicates);
513 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
517 /// Checks whether a trait's method is impossible to call on a given impl.
519 /// This only considers predicates that reference the impl's generics, and not
520 /// those that reference the method's generics.
521 fn is_impossible_method<'tcx>(
523 (impl_def_id, trait_item_def_id): (DefId, DefId),
525 struct ReferencesOnlyParentGenerics<'tcx> {
527 generics: &'tcx ty::Generics,
528 trait_item_def_id: DefId,
530 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
532 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
533 // If this is a parameter from the trait item's own generics, then bail
534 if let ty::Param(param) = t.kind()
535 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
536 && self.tcx.parent(param_def_id) == self.trait_item_def_id
538 return ControlFlow::BREAK;
540 t.super_visit_with(self)
542 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
543 if let ty::ReEarlyBound(param) = r.kind()
544 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
545 && self.tcx.parent(param_def_id) == self.trait_item_def_id
547 return ControlFlow::BREAK;
549 r.super_visit_with(self)
551 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
552 if let ty::ConstKind::Param(param) = ct.kind()
553 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
554 && self.tcx.parent(param_def_id) == self.trait_item_def_id
556 return ControlFlow::BREAK;
558 ct.super_visit_with(self)
562 let generics = tcx.generics_of(trait_item_def_id);
563 let predicates = tcx.predicates_of(trait_item_def_id);
565 tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
566 let param_env = tcx.param_env(impl_def_id);
568 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
569 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
570 if pred.visit_with(&mut visitor).is_continue() {
571 Some(Obligation::new(
572 ObligationCause::dummy_with_span(*span),
574 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
581 tcx.infer_ctxt().ignoring_regions().enter(|ref infcx| {
582 for obligation in predicates_for_trait {
583 // Ignore overflow error, to be conservative.
584 if let Ok(result) = infcx.evaluate_obligation(&obligation)
585 && !result.may_apply()
595 #[derive(Clone, Debug)]
596 enum VtblSegment<'tcx> {
598 TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
601 /// Prepare the segments for a vtable
602 fn prepare_vtable_segments<'tcx, T>(
604 trait_ref: ty::PolyTraitRef<'tcx>,
605 mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
607 // The following constraints holds for the final arrangement.
608 // 1. The whole virtual table of the first direct super trait is included as the
609 // the prefix. If this trait doesn't have any super traits, then this step
610 // consists of the dsa metadata.
611 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
612 // other super traits except those already included as part of the first
613 // direct super trait virtual table.
614 // 3. finally, the own methods of this trait.
616 // This has the advantage that trait upcasting to the first direct super trait on each level
617 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
618 // while not using too much extra memory.
620 // For a single inheritance relationship like this,
621 // D --> C --> B --> A
622 // The resulting vtable will consists of these segments:
625 // For a multiple inheritance relationship like this,
628 // The resulting vtable will consists of these segments:
629 // DSA, A, B, B-vptr, C, D
631 // For a diamond inheritance relationship like this,
634 // The resulting vtable will consists of these segments:
635 // DSA, A, B, C, C-vptr, D
637 // For a more complex inheritance relationship like this:
638 // O --> G --> C --> A
646 // The resulting vtable will consists of these segments:
647 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
648 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
651 // emit dsa segment first.
652 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
656 let mut emit_vptr_on_new_entry = false;
657 let mut visited = util::PredicateSet::new(tcx);
658 let predicate = trait_ref.without_const().to_predicate(tcx);
659 let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
660 smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
661 visited.insert(predicate);
663 // the main traversal loop:
664 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
665 // that each node is emitted after all its descendents have been emitted.
666 // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
667 // this is done on the fly.
668 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
669 // stops after it finds a node that has a next-sibling node.
670 // This next-sibling node will used as the starting point of next slice.
673 // For a diamond inheritance relationship like this,
674 // D#1 --> B#0 --> A#0
677 // Starting point 0 stack [D]
678 // Loop run #0: Stack after diving in is [D B A], A is "childless"
679 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
680 // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
681 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
682 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
683 // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
684 // Loop run #1: Stack after exiting out is []. Now the function exits.
687 // dive deeper into the stack, recording the path
689 if let Some((inner_most_trait_ref, _, _)) = stack.last() {
690 let inner_most_trait_ref = *inner_most_trait_ref;
691 let mut direct_super_traits_iter = tcx
692 .super_predicates_of(inner_most_trait_ref.def_id())
695 .filter_map(move |(pred, _)| {
696 pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
699 'diving_in_skip_visited_traits: loop {
700 if let Some(next_super_trait) = direct_super_traits_iter.next() {
701 if visited.insert(next_super_trait.to_predicate(tcx)) {
702 // We're throwing away potential constness of super traits here.
703 // FIXME: handle ~const super traits
704 let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
707 emit_vptr_on_new_entry,
708 Some(direct_super_traits_iter),
710 break 'diving_in_skip_visited_traits;
712 continue 'diving_in_skip_visited_traits;
721 // Other than the left-most path, vptr should be emitted for each trait.
722 emit_vptr_on_new_entry = true;
724 // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
726 if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
727 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
728 trait_ref: *inner_most_trait_ref,
729 emit_vptr: *emit_vptr,
734 'exiting_out_skip_visited_traits: loop {
735 if let Some(siblings) = siblings_opt {
736 if let Some(next_inner_most_trait_ref) = siblings.next() {
737 if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
738 // We're throwing away potential constness of super traits here.
739 // FIXME: handle ~const super traits
740 let next_inner_most_trait_ref =
741 next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
742 *inner_most_trait_ref = next_inner_most_trait_ref;
743 *emit_vptr = emit_vptr_on_new_entry;
746 continue 'exiting_out_skip_visited_traits;
751 continue 'exiting_out;
760 fn dump_vtable_entries<'tcx>(
763 trait_ref: ty::PolyTraitRef<'tcx>,
764 entries: &[VtblEntry<'tcx>],
766 tcx.sess.emit_err(DumpVTableEntries {
769 entries: format!("{:#?}", entries),
773 fn own_existential_vtable_entries<'tcx>(
775 trait_ref: ty::PolyExistentialTraitRef<'tcx>,
777 let trait_methods = tcx
778 .associated_items(trait_ref.def_id())
779 .in_definition_order()
780 .filter(|item| item.kind == ty::AssocKind::Fn);
781 // Now list each method's DefId (for within its trait).
782 let own_entries = trait_methods.filter_map(move |trait_method| {
783 debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
784 let def_id = trait_method.def_id;
786 // Some methods cannot be called on an object; skip those.
787 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
788 debug!("own_existential_vtable_entry: not vtable safe");
795 tcx.arena.alloc_from_iter(own_entries.into_iter())
798 /// Given a trait `trait_ref`, iterates the vtable entries
799 /// that come from `trait_ref`, including its supertraits.
800 fn vtable_entries<'tcx>(
802 trait_ref: ty::PolyTraitRef<'tcx>,
803 ) -> &'tcx [VtblEntry<'tcx>] {
804 debug!("vtable_entries({:?})", trait_ref);
806 let mut entries = vec![];
808 let vtable_segment_callback = |segment| -> ControlFlow<()> {
810 VtblSegment::MetadataDSA => {
811 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
813 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
814 let existential_trait_ref = trait_ref
815 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
817 // Lookup the shape of vtable for the trait.
818 let own_existential_entries =
819 tcx.own_existential_vtable_entries(existential_trait_ref);
821 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
822 debug!("vtable_entries: trait_method={:?}", def_id);
824 // The method may have some early-bound lifetimes; add regions for those.
825 let substs = trait_ref.map_bound(|trait_ref| {
826 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
827 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
828 GenericParamDefKind::Type { .. }
829 | GenericParamDefKind::Const { .. } => {
830 trait_ref.substs[param.index as usize]
835 // The trait type may have higher-ranked lifetimes in it;
836 // erase them if they appear, so that we get the type
837 // at some particular call site.
839 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
841 // It's possible that the method relies on where-clauses that
842 // do not hold for this particular set of type parameters.
843 // Note that this method could then never be called, so we
844 // do not want to try and codegen it, in that case (see #23435).
845 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
846 if impossible_predicates(tcx, predicates.predicates) {
847 debug!("vtable_entries: predicates do not hold");
848 return VtblEntry::Vacant;
851 let instance = ty::Instance::resolve_for_vtable(
853 ty::ParamEnv::reveal_all(),
857 .expect("resolution failed during building vtable representation");
858 VtblEntry::Method(instance)
861 entries.extend(own_entries);
864 entries.push(VtblEntry::TraitVPtr(trait_ref));
869 ControlFlow::Continue(())
872 let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
874 if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
875 let sp = tcx.def_span(trait_ref.def_id());
876 dump_vtable_entries(tcx, sp, trait_ref, &entries);
879 tcx.arena.alloc_from_iter(entries.into_iter())
882 /// Find slot base for trait methods within vtable entries of another trait
883 fn vtable_trait_first_method_offset<'tcx>(
886 ty::PolyTraitRef<'tcx>, // trait_to_be_found
887 ty::PolyTraitRef<'tcx>, // trait_owning_vtable
890 let (trait_to_be_found, trait_owning_vtable) = key;
893 let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
895 let vtable_segment_callback = {
896 let mut vtable_base = 0;
900 VtblSegment::MetadataDSA => {
901 vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
903 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
904 if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
905 return ControlFlow::Break(vtable_base);
907 vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
913 ControlFlow::Continue(())
917 if let Some(vtable_base) =
918 prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
922 bug!("Failed to find info for expected trait in vtable");
926 /// Find slot offset for trait vptr within vtable entries of another trait
927 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
930 Ty<'tcx>, // trait object type whose trait owning vtable
931 Ty<'tcx>, // trait object for supertrait
934 let (source, target) = key;
935 assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
936 assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
938 // this has been typecked-before, so diagnostics is not really needed.
939 let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
941 let trait_ref = ty::TraitRef {
942 def_id: unsize_trait_did,
943 substs: tcx.mk_substs_trait(source, &[target.into()]),
945 let obligation = Obligation::new(
946 ObligationCause::dummy(),
947 ty::ParamEnv::reveal_all(),
948 ty::Binder::dummy(ty::TraitPredicate {
950 constness: ty::BoundConstness::NotConst,
951 polarity: ty::ImplPolarity::Positive,
955 let implsrc = tcx.infer_ctxt().enter(|infcx| {
956 let mut selcx = SelectionContext::new(&infcx);
957 selcx.select(&obligation).unwrap()
960 let Some(ImplSource::TraitUpcasting(implsrc_traitcasting)) = implsrc else {
964 implsrc_traitcasting.vtable_vptr_slot
967 pub fn provide(providers: &mut ty::query::Providers) {
968 object_safety::provide(providers);
969 structural_match::provide(providers);
970 *providers = ty::query::Providers {
971 specialization_graph_of: specialize::specialization_graph_provider,
972 specializes: specialize::specializes,
973 codegen_select_candidate: codegen::codegen_select_candidate,
974 own_existential_vtable_entries,
976 vtable_trait_upcasting_coercion_new_vptr_slot,
977 subst_and_check_impossible_predicates,
978 is_impossible_method,
979 try_unify_abstract_consts: |tcx, param_env_and| {
980 let (param_env, (a, b)) = param_env_and.into_parts();
981 const_evaluatable::try_unify_abstract_consts(tcx, (a, b), param_env)