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::TypeErrCtxtExt 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<'tcx>(
144 infcx: &InferCtxt<'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_non_region_infer() {
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 let infcx = tcx.infer_ctxt().ignoring_regions().build();
238 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
239 Ok(predicates) => predicates,
241 let reported = infcx.err_ctxt().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(
259 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
263 match infcx.fully_resolve(predicates) {
264 Ok(predicates) => Ok(predicates),
266 // If we encounter a fixup error, it means that some type
267 // variable wound up unconstrained. I actually don't know
268 // if this can happen, and I certainly don't expect it to
269 // happen often, but if it did happen it probably
270 // represents a legitimate failure due to some kind of
271 // unconstrained variable.
273 // @lcnr: Let's still ICE here for now. I want a test case
277 "inference variables in normalized parameter environment: {}",
284 // FIXME: this is gonna need to be removed ...
285 /// Normalizes the parameter environment, reporting errors if they occur.
286 #[instrument(level = "debug", skip(tcx))]
287 pub fn normalize_param_env_or_error<'tcx>(
289 unnormalized_env: ty::ParamEnv<'tcx>,
290 cause: ObligationCause<'tcx>,
291 ) -> ty::ParamEnv<'tcx> {
292 // I'm not wild about reporting errors here; I'd prefer to
293 // have the errors get reported at a defined place (e.g.,
294 // during typeck). Instead I have all parameter
295 // environments, in effect, going through this function
296 // and hence potentially reporting errors. This ensures of
297 // course that we never forget to normalize (the
298 // alternative seemed like it would involve a lot of
299 // manual invocations of this fn -- and then we'd have to
300 // deal with the errors at each of those sites).
302 // In any case, in practice, typeck constructs all the
303 // parameter environments once for every fn as it goes,
304 // and errors will get reported then; so outside of type inference we
305 // can be sure that no errors should occur.
306 let mut predicates: Vec<_> =
307 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
308 .map(|obligation| obligation.predicate)
311 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
313 let elaborated_env = ty::ParamEnv::new(
314 tcx.intern_predicates(&predicates),
315 unnormalized_env.reveal(),
316 unnormalized_env.constness(),
319 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
320 // normalization expects its param-env to be already normalized, which means we have
323 // The way we handle this is by normalizing the param-env inside an unnormalized version
324 // of the param-env, which means that if the param-env contains unnormalized projections,
325 // we'll have some normalization failures. This is unfortunate.
327 // Lazy normalization would basically handle this by treating just the
328 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
330 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
331 // types, so to make the situation less bad, we normalize all the predicates *but*
332 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
333 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
335 // This works fairly well because trait matching does not actually care about param-env
336 // TypeOutlives predicates - these are normally used by regionck.
337 let outlives_predicates: Vec<_> = predicates
338 .drain_filter(|predicate| {
339 matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..))
344 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
345 predicates, outlives_predicates
347 let Ok(non_outlives_predicates) = do_normalize_predicates(
353 // An unnormalized env is better than nothing.
354 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
355 return elaborated_env;
358 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
360 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
361 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
362 // predicates here anyway. Keeping them here anyway because it seems safer.
363 let outlives_env: Vec<_> =
364 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
365 let outlives_env = ty::ParamEnv::new(
366 tcx.intern_predicates(&outlives_env),
367 unnormalized_env.reveal(),
368 unnormalized_env.constness(),
370 let Ok(outlives_predicates) = do_normalize_predicates(
376 // An unnormalized env is better than nothing.
377 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
378 return elaborated_env;
380 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
382 let mut predicates = non_outlives_predicates;
383 predicates.extend(outlives_predicates);
384 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
386 tcx.intern_predicates(&predicates),
387 unnormalized_env.reveal(),
388 unnormalized_env.constness(),
392 /// Normalize a type and process all resulting obligations, returning any errors
393 pub fn fully_normalize<'tcx, T>(
394 infcx: &InferCtxt<'tcx>,
395 cause: ObligationCause<'tcx>,
396 param_env: ty::ParamEnv<'tcx>,
398 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
400 T: TypeFoldable<'tcx>,
402 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
403 let selcx = &mut SelectionContext::new(infcx);
404 let Normalized { value: normalized_value, obligations } =
405 project::normalize(selcx, param_env, cause, value);
407 "fully_normalize: normalized_value={:?} obligations={:?}",
408 normalized_value, obligations
411 let mut fulfill_cx = FulfillmentContext::new();
412 for obligation in obligations {
413 fulfill_cx.register_predicate_obligation(infcx, obligation);
416 debug!("fully_normalize: select_all_or_error start");
417 let errors = fulfill_cx.select_all_or_error(infcx);
418 if !errors.is_empty() {
421 debug!("fully_normalize: select_all_or_error complete");
422 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
423 debug!("fully_normalize: resolved_value={:?}", resolved_value);
427 /// Process an obligation (and any nested obligations that come from it) to
428 /// completion, returning any errors
429 pub fn fully_solve_obligation<'tcx>(
430 infcx: &InferCtxt<'tcx>,
431 obligation: PredicateObligation<'tcx>,
432 ) -> Vec<FulfillmentError<'tcx>> {
433 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
434 engine.register_predicate_obligation(infcx, obligation);
435 engine.select_all_or_error(infcx)
438 /// Process a set of obligations (and any nested obligations that come from them)
440 pub fn fully_solve_obligations<'tcx>(
441 infcx: &InferCtxt<'tcx>,
442 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
443 ) -> Vec<FulfillmentError<'tcx>> {
444 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
445 engine.register_predicate_obligations(infcx, obligations);
446 engine.select_all_or_error(infcx)
449 /// Process a bound (and any nested obligations that come from it) to completion.
450 /// This is a convenience function for traits that have no generic arguments, such
451 /// as auto traits, and builtin traits like Copy or Sized.
452 pub fn fully_solve_bound<'tcx>(
453 infcx: &InferCtxt<'tcx>,
454 cause: ObligationCause<'tcx>,
455 param_env: ty::ParamEnv<'tcx>,
458 ) -> Vec<FulfillmentError<'tcx>> {
459 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
460 engine.register_bound(infcx, param_env, ty, bound, cause);
461 engine.select_all_or_error(infcx)
464 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
465 /// returns true, then either normalize encountered an error or one of the predicates did not
466 /// hold. Used when creating vtables to check for unsatisfiable methods.
467 pub fn impossible_predicates<'tcx>(
469 predicates: Vec<ty::Predicate<'tcx>>,
471 debug!("impossible_predicates(predicates={:?})", predicates);
473 let infcx = tcx.infer_ctxt().build();
474 let param_env = ty::ParamEnv::reveal_all();
475 let ocx = ObligationCtxt::new(&infcx);
476 let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);
477 for predicate in predicates {
478 let obligation = Obligation::new(ObligationCause::dummy(), param_env, predicate);
479 ocx.register_obligation(obligation);
481 let errors = ocx.select_all_or_error();
483 // Clean up after ourselves
484 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
486 let result = !errors.is_empty();
487 debug!("impossible_predicates = {:?}", result);
491 fn subst_and_check_impossible_predicates<'tcx>(
493 key: (DefId, SubstsRef<'tcx>),
495 debug!("subst_and_check_impossible_predicates(key={:?})", key);
497 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
499 // Specifically check trait fulfillment to avoid an error when trying to resolve
501 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
502 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
503 predicates.push(ty::Binder::dummy(trait_ref).to_poly_trait_predicate().to_predicate(tcx));
506 predicates.retain(|predicate| !predicate.needs_subst());
507 let result = impossible_predicates(tcx, predicates);
509 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
513 /// Checks whether a trait's method is impossible to call on a given impl.
515 /// This only considers predicates that reference the impl's generics, and not
516 /// those that reference the method's generics.
517 fn is_impossible_method<'tcx>(
519 (impl_def_id, trait_item_def_id): (DefId, DefId),
521 struct ReferencesOnlyParentGenerics<'tcx> {
523 generics: &'tcx ty::Generics,
524 trait_item_def_id: DefId,
526 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
528 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
529 // If this is a parameter from the trait item's own generics, then bail
530 if let ty::Param(param) = t.kind()
531 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
532 && self.tcx.parent(param_def_id) == self.trait_item_def_id
534 return ControlFlow::BREAK;
536 t.super_visit_with(self)
538 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
539 if let ty::ReEarlyBound(param) = r.kind()
540 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
541 && self.tcx.parent(param_def_id) == self.trait_item_def_id
543 return ControlFlow::BREAK;
545 r.super_visit_with(self)
547 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
548 if let ty::ConstKind::Param(param) = ct.kind()
549 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
550 && self.tcx.parent(param_def_id) == self.trait_item_def_id
552 return ControlFlow::BREAK;
554 ct.super_visit_with(self)
558 let generics = tcx.generics_of(trait_item_def_id);
559 let predicates = tcx.predicates_of(trait_item_def_id);
561 tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
562 let param_env = tcx.param_env(impl_def_id);
564 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
565 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
566 if pred.visit_with(&mut visitor).is_continue() {
567 Some(Obligation::new(
568 ObligationCause::dummy_with_span(*span),
570 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
577 let infcx = tcx.infer_ctxt().ignoring_regions().build();
578 for obligation in predicates_for_trait {
579 // Ignore overflow error, to be conservative.
580 if let Ok(result) = infcx.evaluate_obligation(&obligation)
581 && !result.may_apply()
589 #[derive(Clone, Debug)]
590 enum VtblSegment<'tcx> {
592 TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
595 /// Prepare the segments for a vtable
596 fn prepare_vtable_segments<'tcx, T>(
598 trait_ref: ty::PolyTraitRef<'tcx>,
599 mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
601 // The following constraints holds for the final arrangement.
602 // 1. The whole virtual table of the first direct super trait is included as the
603 // the prefix. If this trait doesn't have any super traits, then this step
604 // consists of the dsa metadata.
605 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
606 // other super traits except those already included as part of the first
607 // direct super trait virtual table.
608 // 3. finally, the own methods of this trait.
610 // This has the advantage that trait upcasting to the first direct super trait on each level
611 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
612 // while not using too much extra memory.
614 // For a single inheritance relationship like this,
615 // D --> C --> B --> A
616 // The resulting vtable will consists of these segments:
619 // For a multiple inheritance relationship like this,
622 // The resulting vtable will consists of these segments:
623 // DSA, A, B, B-vptr, C, D
625 // For a diamond inheritance relationship like this,
628 // The resulting vtable will consists of these segments:
629 // DSA, A, B, C, C-vptr, D
631 // For a more complex inheritance relationship like this:
632 // O --> G --> C --> A
640 // The resulting vtable will consists of these segments:
641 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
642 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
645 // emit dsa segment first.
646 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
650 let mut emit_vptr_on_new_entry = false;
651 let mut visited = util::PredicateSet::new(tcx);
652 let predicate = trait_ref.without_const().to_predicate(tcx);
653 let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
654 smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
655 visited.insert(predicate);
657 // the main traversal loop:
658 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
659 // that each node is emitted after all its descendents have been emitted.
660 // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
661 // this is done on the fly.
662 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
663 // stops after it finds a node that has a next-sibling node.
664 // This next-sibling node will used as the starting point of next slice.
667 // For a diamond inheritance relationship like this,
668 // D#1 --> B#0 --> A#0
671 // Starting point 0 stack [D]
672 // Loop run #0: Stack after diving in is [D B A], A is "childless"
673 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
674 // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
675 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
676 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
677 // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
678 // Loop run #1: Stack after exiting out is []. Now the function exits.
681 // dive deeper into the stack, recording the path
683 if let Some((inner_most_trait_ref, _, _)) = stack.last() {
684 let inner_most_trait_ref = *inner_most_trait_ref;
685 let mut direct_super_traits_iter = tcx
686 .super_predicates_of(inner_most_trait_ref.def_id())
689 .filter_map(move |(pred, _)| {
690 pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
693 'diving_in_skip_visited_traits: loop {
694 if let Some(next_super_trait) = direct_super_traits_iter.next() {
695 if visited.insert(next_super_trait.to_predicate(tcx)) {
696 // We're throwing away potential constness of super traits here.
697 // FIXME: handle ~const super traits
698 let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
701 emit_vptr_on_new_entry,
702 Some(direct_super_traits_iter),
704 break 'diving_in_skip_visited_traits;
706 continue 'diving_in_skip_visited_traits;
715 // Other than the left-most path, vptr should be emitted for each trait.
716 emit_vptr_on_new_entry = true;
718 // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
720 if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
721 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
722 trait_ref: *inner_most_trait_ref,
723 emit_vptr: *emit_vptr,
728 'exiting_out_skip_visited_traits: loop {
729 if let Some(siblings) = siblings_opt {
730 if let Some(next_inner_most_trait_ref) = siblings.next() {
731 if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
732 // We're throwing away potential constness of super traits here.
733 // FIXME: handle ~const super traits
734 let next_inner_most_trait_ref =
735 next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
736 *inner_most_trait_ref = next_inner_most_trait_ref;
737 *emit_vptr = emit_vptr_on_new_entry;
740 continue 'exiting_out_skip_visited_traits;
745 continue 'exiting_out;
754 fn dump_vtable_entries<'tcx>(
757 trait_ref: ty::PolyTraitRef<'tcx>,
758 entries: &[VtblEntry<'tcx>],
760 tcx.sess.emit_err(DumpVTableEntries {
763 entries: format!("{:#?}", entries),
767 fn own_existential_vtable_entries<'tcx>(
769 trait_ref: ty::PolyExistentialTraitRef<'tcx>,
771 let trait_methods = tcx
772 .associated_items(trait_ref.def_id())
773 .in_definition_order()
774 .filter(|item| item.kind == ty::AssocKind::Fn);
775 // Now list each method's DefId (for within its trait).
776 let own_entries = trait_methods.filter_map(move |trait_method| {
777 debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
778 let def_id = trait_method.def_id;
780 // Some methods cannot be called on an object; skip those.
781 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
782 debug!("own_existential_vtable_entry: not vtable safe");
789 tcx.arena.alloc_from_iter(own_entries.into_iter())
792 /// Given a trait `trait_ref`, iterates the vtable entries
793 /// that come from `trait_ref`, including its supertraits.
794 fn vtable_entries<'tcx>(
796 trait_ref: ty::PolyTraitRef<'tcx>,
797 ) -> &'tcx [VtblEntry<'tcx>] {
798 debug!("vtable_entries({:?})", trait_ref);
800 let mut entries = vec![];
802 let vtable_segment_callback = |segment| -> ControlFlow<()> {
804 VtblSegment::MetadataDSA => {
805 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
807 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
808 let existential_trait_ref = trait_ref
809 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
811 // Lookup the shape of vtable for the trait.
812 let own_existential_entries =
813 tcx.own_existential_vtable_entries(existential_trait_ref);
815 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
816 debug!("vtable_entries: trait_method={:?}", def_id);
818 // The method may have some early-bound lifetimes; add regions for those.
819 let substs = trait_ref.map_bound(|trait_ref| {
820 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
821 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
822 GenericParamDefKind::Type { .. }
823 | GenericParamDefKind::Const { .. } => {
824 trait_ref.substs[param.index as usize]
829 // The trait type may have higher-ranked lifetimes in it;
830 // erase them if they appear, so that we get the type
831 // at some particular call site.
833 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
835 // It's possible that the method relies on where-clauses that
836 // do not hold for this particular set of type parameters.
837 // Note that this method could then never be called, so we
838 // do not want to try and codegen it, in that case (see #23435).
839 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
840 if impossible_predicates(tcx, predicates.predicates) {
841 debug!("vtable_entries: predicates do not hold");
842 return VtblEntry::Vacant;
845 let instance = ty::Instance::resolve_for_vtable(
847 ty::ParamEnv::reveal_all(),
851 .expect("resolution failed during building vtable representation");
852 VtblEntry::Method(instance)
855 entries.extend(own_entries);
858 entries.push(VtblEntry::TraitVPtr(trait_ref));
863 ControlFlow::Continue(())
866 let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
868 if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
869 let sp = tcx.def_span(trait_ref.def_id());
870 dump_vtable_entries(tcx, sp, trait_ref, &entries);
873 tcx.arena.alloc_from_iter(entries.into_iter())
876 /// Find slot base for trait methods within vtable entries of another trait
877 fn vtable_trait_first_method_offset<'tcx>(
880 ty::PolyTraitRef<'tcx>, // trait_to_be_found
881 ty::PolyTraitRef<'tcx>, // trait_owning_vtable
884 let (trait_to_be_found, trait_owning_vtable) = key;
887 let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
889 let vtable_segment_callback = {
890 let mut vtable_base = 0;
894 VtblSegment::MetadataDSA => {
895 vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
897 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
898 if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
899 return ControlFlow::Break(vtable_base);
901 vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
907 ControlFlow::Continue(())
911 if let Some(vtable_base) =
912 prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
916 bug!("Failed to find info for expected trait in vtable");
920 /// Find slot offset for trait vptr within vtable entries of another trait
921 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
924 Ty<'tcx>, // trait object type whose trait owning vtable
925 Ty<'tcx>, // trait object for supertrait
928 let (source, target) = key;
929 assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
930 assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
932 // this has been typecked-before, so diagnostics is not really needed.
933 let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
935 let trait_ref = ty::TraitRef {
936 def_id: unsize_trait_did,
937 substs: tcx.mk_substs_trait(source, &[target.into()]),
939 let obligation = Obligation::new(
940 ObligationCause::dummy(),
941 ty::ParamEnv::reveal_all(),
942 ty::Binder::dummy(ty::TraitPredicate {
944 constness: ty::BoundConstness::NotConst,
945 polarity: ty::ImplPolarity::Positive,
949 let infcx = tcx.infer_ctxt().build();
950 let mut selcx = SelectionContext::new(&infcx);
951 let implsrc = selcx.select(&obligation).unwrap();
953 let Some(ImplSource::TraitUpcasting(implsrc_traitcasting)) = implsrc else {
957 implsrc_traitcasting.vtable_vptr_slot
960 pub fn provide(providers: &mut ty::query::Providers) {
961 object_safety::provide(providers);
962 structural_match::provide(providers);
963 *providers = ty::query::Providers {
964 specialization_graph_of: specialize::specialization_graph_provider,
965 specializes: specialize::specializes,
966 codegen_select_candidate: codegen::codegen_select_candidate,
967 own_existential_vtable_entries,
969 vtable_trait_upcasting_coercion_new_vptr_slot,
970 subst_and_check_impossible_predicates,
971 is_impossible_method,
972 try_unify_abstract_consts: |tcx, param_env_and| {
973 let (param_env, (a, b)) = param_env_and.into_parts();
974 const_evaluatable::try_unify_abstract_consts(tcx, (a, b), param_env)