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;
15 pub mod outlives_bounds;
18 pub(crate) mod relationships;
25 use crate::errors::DumpVTableEntries;
26 use crate::infer::outlives::env::OutlivesEnvironment;
27 use crate::infer::{InferCtxt, TyCtxtInferExt};
28 use crate::traits::error_reporting::TypeErrCtxtExt as _;
29 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
30 use rustc_errors::ErrorGuaranteed;
32 use rustc_hir::def_id::DefId;
33 use rustc_hir::lang_items::LangItem;
34 use rustc_middle::ty::fold::TypeFoldable;
35 use rustc_middle::ty::visit::TypeVisitable;
36 use rustc_middle::ty::{
37 self, DefIdTree, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeSuperVisitable, VtblEntry,
39 use rustc_middle::ty::{InternalSubsts, SubstsRef};
40 use rustc_span::{sym, Span};
41 use smallvec::SmallVec;
44 use std::ops::ControlFlow;
46 pub use self::FulfillmentErrorCode::*;
47 pub use self::ImplSource::*;
48 pub use self::ObligationCauseCode::*;
49 pub use self::SelectionError::*;
51 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
52 pub use self::coherence::{OrphanCheckErr, OverlapResult};
53 pub use self::engine::{ObligationCtxt, TraitEngineExt};
54 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
55 pub use self::object_safety::astconv_object_safety_violations;
56 pub use self::object_safety::is_vtable_safe_method;
57 pub use self::object_safety::MethodViolationCode;
58 pub use self::object_safety::ObjectSafetyViolation;
59 pub use self::project::{normalize, normalize_projection_type, normalize_to};
60 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
61 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
62 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
63 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
64 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
65 pub use self::structural_match::{
66 search_for_adt_const_param_violation, search_for_structural_match_violation,
69 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
70 elaborate_trait_ref, elaborate_trait_refs,
72 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
74 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
77 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
78 SupertraitDefIds, Supertraits,
81 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
83 pub use rustc_infer::traits::*;
85 /// Whether to skip the leak check, as part of a future compatibility warning step.
87 /// The "default" for skip-leak-check corresponds to the current
88 /// behavior (do not skip the leak check) -- not the behavior we are
89 /// transitioning into.
90 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
91 pub enum SkipLeakCheck {
98 fn is_yes(self) -> bool {
99 self == SkipLeakCheck::Yes
103 /// The mode that trait queries run in.
104 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
105 pub enum TraitQueryMode {
106 /// Standard/un-canonicalized queries get accurate
107 /// spans etc. passed in and hence can do reasonable
108 /// error reporting on their own.
110 /// Canonicalized queries get dummy spans and hence
111 /// must generally propagate errors to
112 /// pre-canonicalization callsites.
116 /// Creates predicate obligations from the generic bounds.
117 #[instrument(level = "debug", skip(cause, param_env))]
118 pub fn predicates_for_generics<'tcx>(
119 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
120 param_env: ty::ParamEnv<'tcx>,
121 generic_bounds: ty::InstantiatedPredicates<'tcx>,
122 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
123 std::iter::zip(generic_bounds.predicates, generic_bounds.spans).enumerate().map(
124 move |(idx, (predicate, span))| Obligation {
125 cause: cause(idx, span),
133 /// Determines whether the type `ty` is known to meet `bound` and
134 /// returns true if so. Returns false if `ty` either does not meet
135 /// `bound` or is not known to meet bound (note that this is
136 /// conservative towards *no impl*, which is the opposite of the
137 /// `evaluate` methods).
138 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
139 infcx: &InferCtxt<'tcx>,
140 param_env: ty::ParamEnv<'tcx>,
145 let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
146 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
149 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
150 fn pred_known_to_hold_modulo_regions<'tcx>(
151 infcx: &InferCtxt<'tcx>,
152 param_env: ty::ParamEnv<'tcx>,
153 pred: impl ToPredicate<'tcx, ty::Predicate<'tcx>> + TypeVisitable<'tcx>,
156 let has_non_region_infer = pred.has_non_region_infer();
157 let obligation = Obligation {
159 // We can use a dummy node-id here because we won't pay any mind
160 // to region obligations that arise (there shouldn't really be any
162 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
164 predicate: pred.to_predicate(infcx.tcx),
167 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
170 if result && has_non_region_infer {
171 // Because of inference "guessing", selection can sometimes claim
172 // to succeed while the success requires a guess. To ensure
173 // this function's result remains infallible, we must confirm
174 // that guess. While imperfect, I believe this is sound.
176 // FIXME(@lcnr): this function doesn't seem right.
177 // The handling of regions in this area of the code is terrible,
178 // see issue #29149. We should be able to improve on this with
180 let errors = fully_solve_obligation(infcx, obligation);
182 // Note: we only assume something is `Copy` if we can
183 // *definitively* show that it implements `Copy`. Otherwise,
184 // assume it is move; linear is always ok.
197 #[instrument(level = "debug", skip(tcx, elaborated_env))]
198 fn do_normalize_predicates<'tcx>(
200 cause: ObligationCause<'tcx>,
201 elaborated_env: ty::ParamEnv<'tcx>,
202 predicates: Vec<ty::Predicate<'tcx>>,
203 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
204 let span = cause.span;
205 // FIXME. We should really... do something with these region
206 // obligations. But this call just continues the older
207 // behavior (i.e., doesn't cause any new bugs), and it would
208 // take some further refactoring to actually solve them. In
209 // particular, we would have to handle implied bounds
210 // properly, and that code is currently largely confined to
211 // regionck (though I made some efforts to extract it
214 // @arielby: In any case, these obligations are checked
215 // by wfcheck anyway, so I'm not sure we have to check
216 // them here too, and we will remove this function when
217 // we move over to lazy normalization *anyway*.
218 let infcx = tcx.infer_ctxt().ignoring_regions().build();
219 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
220 Ok(predicates) => predicates,
222 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
223 return Err(reported);
227 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
229 // We can use the `elaborated_env` here; the region code only
230 // cares about declarations like `'a: 'b`.
231 let outlives_env = OutlivesEnvironment::new(elaborated_env);
233 // FIXME: It's very weird that we ignore region obligations but apparently
234 // still need to use `resolve_regions` as we need the resolved regions in
235 // the normalized predicates.
236 let errors = infcx.resolve_regions(&outlives_env);
237 if !errors.is_empty() {
238 tcx.sess.delay_span_bug(
240 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
244 match infcx.fully_resolve(predicates) {
245 Ok(predicates) => Ok(predicates),
247 // If we encounter a fixup error, it means that some type
248 // variable wound up unconstrained. I actually don't know
249 // if this can happen, and I certainly don't expect it to
250 // happen often, but if it did happen it probably
251 // represents a legitimate failure due to some kind of
252 // unconstrained variable.
254 // @lcnr: Let's still ICE here for now. I want a test case
258 "inference variables in normalized parameter environment: {}",
265 // FIXME: this is gonna need to be removed ...
266 /// Normalizes the parameter environment, reporting errors if they occur.
267 #[instrument(level = "debug", skip(tcx))]
268 pub fn normalize_param_env_or_error<'tcx>(
270 unnormalized_env: ty::ParamEnv<'tcx>,
271 cause: ObligationCause<'tcx>,
272 ) -> ty::ParamEnv<'tcx> {
273 // I'm not wild about reporting errors here; I'd prefer to
274 // have the errors get reported at a defined place (e.g.,
275 // during typeck). Instead I have all parameter
276 // environments, in effect, going through this function
277 // and hence potentially reporting errors. This ensures of
278 // course that we never forget to normalize (the
279 // alternative seemed like it would involve a lot of
280 // manual invocations of this fn -- and then we'd have to
281 // deal with the errors at each of those sites).
283 // In any case, in practice, typeck constructs all the
284 // parameter environments once for every fn as it goes,
285 // and errors will get reported then; so outside of type inference we
286 // can be sure that no errors should occur.
287 let mut predicates: Vec<_> =
288 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
289 .map(|obligation| obligation.predicate)
292 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
294 let elaborated_env = ty::ParamEnv::new(
295 tcx.intern_predicates(&predicates),
296 unnormalized_env.reveal(),
297 unnormalized_env.constness(),
300 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
301 // normalization expects its param-env to be already normalized, which means we have
304 // The way we handle this is by normalizing the param-env inside an unnormalized version
305 // of the param-env, which means that if the param-env contains unnormalized projections,
306 // we'll have some normalization failures. This is unfortunate.
308 // Lazy normalization would basically handle this by treating just the
309 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
311 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
312 // types, so to make the situation less bad, we normalize all the predicates *but*
313 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
314 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
316 // This works fairly well because trait matching does not actually care about param-env
317 // TypeOutlives predicates - these are normally used by regionck.
318 let outlives_predicates: Vec<_> = predicates
319 .drain_filter(|predicate| {
321 predicate.kind().skip_binder(),
322 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
328 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
329 predicates, outlives_predicates
331 let Ok(non_outlives_predicates) = do_normalize_predicates(
337 // An unnormalized env is better than nothing.
338 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
339 return elaborated_env;
342 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
344 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
345 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
346 // predicates here anyway. Keeping them here anyway because it seems safer.
347 let outlives_env: Vec<_> =
348 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
349 let outlives_env = ty::ParamEnv::new(
350 tcx.intern_predicates(&outlives_env),
351 unnormalized_env.reveal(),
352 unnormalized_env.constness(),
354 let Ok(outlives_predicates) = do_normalize_predicates(
360 // An unnormalized env is better than nothing.
361 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
362 return elaborated_env;
364 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
366 let mut predicates = non_outlives_predicates;
367 predicates.extend(outlives_predicates);
368 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
370 tcx.intern_predicates(&predicates),
371 unnormalized_env.reveal(),
372 unnormalized_env.constness(),
376 /// Normalize a type and process all resulting obligations, returning any errors
377 #[instrument(skip_all)]
378 pub fn fully_normalize<'tcx, T>(
379 infcx: &InferCtxt<'tcx>,
380 cause: ObligationCause<'tcx>,
381 param_env: ty::ParamEnv<'tcx>,
383 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
385 T: TypeFoldable<'tcx>,
387 let ocx = ObligationCtxt::new(infcx);
389 let normalized_value = ocx.normalize(cause, param_env, value);
390 debug!(?normalized_value);
391 debug!("select_all_or_error start");
392 let errors = ocx.select_all_or_error();
393 if !errors.is_empty() {
396 debug!("select_all_or_error complete");
397 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
398 debug!(?resolved_value);
402 /// Process an obligation (and any nested obligations that come from it) to
403 /// completion, returning any errors
404 pub fn fully_solve_obligation<'tcx>(
405 infcx: &InferCtxt<'tcx>,
406 obligation: PredicateObligation<'tcx>,
407 ) -> Vec<FulfillmentError<'tcx>> {
408 fully_solve_obligations(infcx, [obligation])
411 /// Process a set of obligations (and any nested obligations that come from them)
413 pub fn fully_solve_obligations<'tcx>(
414 infcx: &InferCtxt<'tcx>,
415 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
416 ) -> Vec<FulfillmentError<'tcx>> {
417 let ocx = ObligationCtxt::new(infcx);
418 ocx.register_obligations(obligations);
419 ocx.select_all_or_error()
422 /// Process a bound (and any nested obligations that come from it) to completion.
423 /// This is a convenience function for traits that have no generic arguments, such
424 /// as auto traits, and builtin traits like Copy or Sized.
425 pub fn fully_solve_bound<'tcx>(
426 infcx: &InferCtxt<'tcx>,
427 cause: ObligationCause<'tcx>,
428 param_env: ty::ParamEnv<'tcx>,
431 ) -> Vec<FulfillmentError<'tcx>> {
433 let trait_ref = ty::TraitRef { def_id: bound, substs: tcx.mk_substs_trait(ty, []) };
434 let obligation = Obligation {
438 predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
441 fully_solve_obligation(infcx, obligation)
444 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
445 /// returns true, then either normalize encountered an error or one of the predicates did not
446 /// hold. Used when creating vtables to check for unsatisfiable methods.
447 pub fn impossible_predicates<'tcx>(
449 predicates: Vec<ty::Predicate<'tcx>>,
451 debug!("impossible_predicates(predicates={:?})", predicates);
453 let infcx = tcx.infer_ctxt().build();
454 let param_env = ty::ParamEnv::reveal_all();
455 let ocx = ObligationCtxt::new(&infcx);
456 let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);
457 for predicate in predicates {
458 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
459 ocx.register_obligation(obligation);
461 let errors = ocx.select_all_or_error();
463 // Clean up after ourselves
464 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
466 let result = !errors.is_empty();
467 debug!("impossible_predicates = {:?}", result);
471 fn subst_and_check_impossible_predicates<'tcx>(
473 key: (DefId, SubstsRef<'tcx>),
475 debug!("subst_and_check_impossible_predicates(key={:?})", key);
477 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
479 // Specifically check trait fulfillment to avoid an error when trying to resolve
481 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
482 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
483 predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
486 predicates.retain(|predicate| !predicate.needs_subst());
487 let result = impossible_predicates(tcx, predicates);
489 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
493 /// Checks whether a trait's method is impossible to call on a given impl.
495 /// This only considers predicates that reference the impl's generics, and not
496 /// those that reference the method's generics.
497 fn is_impossible_method<'tcx>(
499 (impl_def_id, trait_item_def_id): (DefId, DefId),
501 struct ReferencesOnlyParentGenerics<'tcx> {
503 generics: &'tcx ty::Generics,
504 trait_item_def_id: DefId,
506 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
508 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
509 // If this is a parameter from the trait item's own generics, then bail
510 if let ty::Param(param) = t.kind()
511 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
512 && self.tcx.parent(param_def_id) == self.trait_item_def_id
514 return ControlFlow::BREAK;
516 t.super_visit_with(self)
518 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
519 if let ty::ReEarlyBound(param) = r.kind()
520 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
521 && self.tcx.parent(param_def_id) == self.trait_item_def_id
523 return ControlFlow::BREAK;
525 r.super_visit_with(self)
527 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
528 if let ty::ConstKind::Param(param) = ct.kind()
529 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
530 && self.tcx.parent(param_def_id) == self.trait_item_def_id
532 return ControlFlow::BREAK;
534 ct.super_visit_with(self)
538 let generics = tcx.generics_of(trait_item_def_id);
539 let predicates = tcx.predicates_of(trait_item_def_id);
541 tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
542 let param_env = tcx.param_env(impl_def_id);
544 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
545 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
546 if pred.visit_with(&mut visitor).is_continue() {
547 Some(Obligation::new(
549 ObligationCause::dummy_with_span(*span),
551 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
558 let infcx = tcx.infer_ctxt().ignoring_regions().build();
559 for obligation in predicates_for_trait {
560 // Ignore overflow error, to be conservative.
561 if let Ok(result) = infcx.evaluate_obligation(&obligation)
562 && !result.may_apply()
570 #[derive(Clone, Debug)]
571 enum VtblSegment<'tcx> {
573 TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
576 /// Prepare the segments for a vtable
577 fn prepare_vtable_segments<'tcx, T>(
579 trait_ref: ty::PolyTraitRef<'tcx>,
580 mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
582 // The following constraints holds for the final arrangement.
583 // 1. The whole virtual table of the first direct super trait is included as the
584 // the prefix. If this trait doesn't have any super traits, then this step
585 // consists of the dsa metadata.
586 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
587 // other super traits except those already included as part of the first
588 // direct super trait virtual table.
589 // 3. finally, the own methods of this trait.
591 // This has the advantage that trait upcasting to the first direct super trait on each level
592 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
593 // while not using too much extra memory.
595 // For a single inheritance relationship like this,
596 // D --> C --> B --> A
597 // The resulting vtable will consists of these segments:
600 // For a multiple inheritance relationship like this,
603 // The resulting vtable will consists of these segments:
604 // DSA, A, B, B-vptr, C, D
606 // For a diamond inheritance relationship like this,
609 // The resulting vtable will consists of these segments:
610 // DSA, A, B, C, C-vptr, D
612 // For a more complex inheritance relationship like this:
613 // O --> G --> C --> A
621 // The resulting vtable will consists of these segments:
622 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
623 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
626 // emit dsa segment first.
627 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
631 let mut emit_vptr_on_new_entry = false;
632 let mut visited = util::PredicateSet::new(tcx);
633 let predicate = trait_ref.without_const().to_predicate(tcx);
634 let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
635 smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
636 visited.insert(predicate);
638 // the main traversal loop:
639 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
640 // that each node is emitted after all its descendents have been emitted.
641 // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
642 // this is done on the fly.
643 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
644 // stops after it finds a node that has a next-sibling node.
645 // This next-sibling node will used as the starting point of next slice.
648 // For a diamond inheritance relationship like this,
649 // D#1 --> B#0 --> A#0
652 // Starting point 0 stack [D]
653 // Loop run #0: Stack after diving in is [D B A], A is "childless"
654 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
655 // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
656 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
657 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
658 // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
659 // Loop run #1: Stack after exiting out is []. Now the function exits.
662 // dive deeper into the stack, recording the path
664 if let Some((inner_most_trait_ref, _, _)) = stack.last() {
665 let inner_most_trait_ref = *inner_most_trait_ref;
666 let mut direct_super_traits_iter = tcx
667 .super_predicates_of(inner_most_trait_ref.def_id())
670 .filter_map(move |(pred, _)| {
671 pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
674 'diving_in_skip_visited_traits: loop {
675 if let Some(next_super_trait) = direct_super_traits_iter.next() {
676 if visited.insert(next_super_trait.to_predicate(tcx)) {
677 // We're throwing away potential constness of super traits here.
678 // FIXME: handle ~const super traits
679 let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
682 emit_vptr_on_new_entry,
683 Some(direct_super_traits_iter),
685 break 'diving_in_skip_visited_traits;
687 continue 'diving_in_skip_visited_traits;
696 // Other than the left-most path, vptr should be emitted for each trait.
697 emit_vptr_on_new_entry = true;
699 // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
701 if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
702 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
703 trait_ref: *inner_most_trait_ref,
704 emit_vptr: *emit_vptr,
709 'exiting_out_skip_visited_traits: loop {
710 if let Some(siblings) = siblings_opt {
711 if let Some(next_inner_most_trait_ref) = siblings.next() {
712 if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
713 // We're throwing away potential constness of super traits here.
714 // FIXME: handle ~const super traits
715 let next_inner_most_trait_ref =
716 next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
717 *inner_most_trait_ref = next_inner_most_trait_ref;
718 *emit_vptr = emit_vptr_on_new_entry;
721 continue 'exiting_out_skip_visited_traits;
726 continue 'exiting_out;
735 fn dump_vtable_entries<'tcx>(
738 trait_ref: ty::PolyTraitRef<'tcx>,
739 entries: &[VtblEntry<'tcx>],
741 tcx.sess.emit_err(DumpVTableEntries {
744 entries: format!("{:#?}", entries),
748 fn own_existential_vtable_entries<'tcx>(tcx: TyCtxt<'tcx>, trait_def_id: DefId) -> &'tcx [DefId] {
749 let trait_methods = tcx
750 .associated_items(trait_def_id)
751 .in_definition_order()
752 .filter(|item| item.kind == ty::AssocKind::Fn);
753 // Now list each method's DefId (for within its trait).
754 let own_entries = trait_methods.filter_map(move |trait_method| {
755 debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
756 let def_id = trait_method.def_id;
758 // Some methods cannot be called on an object; skip those.
759 if !is_vtable_safe_method(tcx, trait_def_id, &trait_method) {
760 debug!("own_existential_vtable_entry: not vtable safe");
767 tcx.arena.alloc_from_iter(own_entries.into_iter())
770 /// Given a trait `trait_ref`, iterates the vtable entries
771 /// that come from `trait_ref`, including its supertraits.
772 fn vtable_entries<'tcx>(
774 trait_ref: ty::PolyTraitRef<'tcx>,
775 ) -> &'tcx [VtblEntry<'tcx>] {
776 debug!("vtable_entries({:?})", trait_ref);
778 let mut entries = vec![];
780 let vtable_segment_callback = |segment| -> ControlFlow<()> {
782 VtblSegment::MetadataDSA => {
783 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
785 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
786 let existential_trait_ref = trait_ref
787 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
789 // Lookup the shape of vtable for the trait.
790 let own_existential_entries =
791 tcx.own_existential_vtable_entries(existential_trait_ref.def_id());
793 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
794 debug!("vtable_entries: trait_method={:?}", def_id);
796 // The method may have some early-bound lifetimes; add regions for those.
797 let substs = trait_ref.map_bound(|trait_ref| {
798 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
799 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
800 GenericParamDefKind::Type { .. }
801 | GenericParamDefKind::Const { .. } => {
802 trait_ref.substs[param.index as usize]
807 // The trait type may have higher-ranked lifetimes in it;
808 // erase them if they appear, so that we get the type
809 // at some particular call site.
811 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
813 // It's possible that the method relies on where-clauses that
814 // do not hold for this particular set of type parameters.
815 // Note that this method could then never be called, so we
816 // do not want to try and codegen it, in that case (see #23435).
817 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
818 if impossible_predicates(tcx, predicates.predicates) {
819 debug!("vtable_entries: predicates do not hold");
820 return VtblEntry::Vacant;
823 let instance = ty::Instance::resolve_for_vtable(
825 ty::ParamEnv::reveal_all(),
829 .expect("resolution failed during building vtable representation");
830 VtblEntry::Method(instance)
833 entries.extend(own_entries);
836 entries.push(VtblEntry::TraitVPtr(trait_ref));
841 ControlFlow::Continue(())
844 let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
846 if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
847 let sp = tcx.def_span(trait_ref.def_id());
848 dump_vtable_entries(tcx, sp, trait_ref, &entries);
851 tcx.arena.alloc_from_iter(entries.into_iter())
854 /// Find slot base for trait methods within vtable entries of another trait
855 fn vtable_trait_first_method_offset<'tcx>(
858 ty::PolyTraitRef<'tcx>, // trait_to_be_found
859 ty::PolyTraitRef<'tcx>, // trait_owning_vtable
862 let (trait_to_be_found, trait_owning_vtable) = key;
865 let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
867 let vtable_segment_callback = {
868 let mut vtable_base = 0;
872 VtblSegment::MetadataDSA => {
873 vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
875 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
876 if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
877 return ControlFlow::Break(vtable_base);
879 vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
885 ControlFlow::Continue(())
889 if let Some(vtable_base) =
890 prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
894 bug!("Failed to find info for expected trait in vtable");
898 /// Find slot offset for trait vptr within vtable entries of another trait
899 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
902 Ty<'tcx>, // trait object type whose trait owning vtable
903 Ty<'tcx>, // trait object for supertrait
906 let (source, target) = key;
907 assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
908 assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
910 // this has been typecked-before, so diagnostics is not really needed.
911 let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
913 let trait_ref = tcx.mk_trait_ref(unsize_trait_did, [source, target]);
915 match tcx.codegen_select_candidate((ty::ParamEnv::reveal_all(), ty::Binder::dummy(trait_ref))) {
916 Ok(ImplSource::TraitUpcasting(implsrc_traitcasting)) => {
917 implsrc_traitcasting.vtable_vptr_slot
919 otherwise => bug!("expected TraitUpcasting candidate, got {otherwise:?}"),
923 pub fn provide(providers: &mut ty::query::Providers) {
924 object_safety::provide(providers);
925 structural_match::provide(providers);
926 *providers = ty::query::Providers {
927 specialization_graph_of: specialize::specialization_graph_provider,
928 specializes: specialize::specializes,
929 codegen_select_candidate: codegen::codegen_select_candidate,
930 own_existential_vtable_entries,
932 vtable_trait_upcasting_coercion_new_vptr_slot,
933 subst_and_check_impossible_predicates,
934 is_impossible_method,