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(crate) use self::project::{normalize, normalize_to};
60 pub use self::project::{normalize_projection_type, NormalizeExt};
61 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
62 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
63 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
64 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
65 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
66 pub use self::structural_match::{
67 search_for_adt_const_param_violation, search_for_structural_match_violation,
70 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
71 elaborate_trait_ref, elaborate_trait_refs,
73 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
75 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
78 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
79 SupertraitDefIds, Supertraits,
82 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
84 pub use rustc_infer::traits::*;
86 /// Whether to skip the leak check, as part of a future compatibility warning step.
88 /// The "default" for skip-leak-check corresponds to the current
89 /// behavior (do not skip the leak check) -- not the behavior we are
90 /// transitioning into.
91 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
92 pub enum SkipLeakCheck {
99 fn is_yes(self) -> bool {
100 self == SkipLeakCheck::Yes
104 /// The mode that trait queries run in.
105 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
106 pub enum TraitQueryMode {
107 /// Standard/un-canonicalized queries get accurate
108 /// spans etc. passed in and hence can do reasonable
109 /// error reporting on their own.
111 /// Canonicalized queries get dummy spans and hence
112 /// must generally propagate errors to
113 /// pre-canonicalization callsites.
117 /// Creates predicate obligations from the generic bounds.
118 #[instrument(level = "debug", skip(cause, param_env))]
119 pub fn predicates_for_generics<'tcx>(
120 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
121 param_env: ty::ParamEnv<'tcx>,
122 generic_bounds: ty::InstantiatedPredicates<'tcx>,
123 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
124 std::iter::zip(generic_bounds.predicates, generic_bounds.spans).enumerate().map(
125 move |(idx, (predicate, span))| Obligation {
126 cause: cause(idx, span),
134 /// Determines whether the type `ty` is known to meet `bound` and
135 /// returns true if so. Returns false if `ty` either does not meet
136 /// `bound` or is not known to meet bound (note that this is
137 /// conservative towards *no impl*, which is the opposite of the
138 /// `evaluate` methods).
139 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
140 infcx: &InferCtxt<'tcx>,
141 param_env: ty::ParamEnv<'tcx>,
146 let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
147 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
150 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
151 fn pred_known_to_hold_modulo_regions<'tcx>(
152 infcx: &InferCtxt<'tcx>,
153 param_env: ty::ParamEnv<'tcx>,
154 pred: impl ToPredicate<'tcx, ty::Predicate<'tcx>> + TypeVisitable<'tcx>,
157 let has_non_region_infer = pred.has_non_region_infer();
158 let obligation = Obligation {
160 // We can use a dummy node-id here because we won't pay any mind
161 // to region obligations that arise (there shouldn't really be any
163 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
165 predicate: pred.to_predicate(infcx.tcx),
168 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
171 if result && has_non_region_infer {
172 // Because of inference "guessing", selection can sometimes claim
173 // to succeed while the success requires a guess. To ensure
174 // this function's result remains infallible, we must confirm
175 // that guess. While imperfect, I believe this is sound.
177 // FIXME(@lcnr): this function doesn't seem right.
178 // The handling of regions in this area of the code is terrible,
179 // see issue #29149. We should be able to improve on this with
181 let errors = fully_solve_obligation(infcx, obligation);
183 // Note: we only assume something is `Copy` if we can
184 // *definitively* show that it implements `Copy`. Otherwise,
185 // assume it is move; linear is always ok.
198 #[instrument(level = "debug", skip(tcx, elaborated_env))]
199 fn do_normalize_predicates<'tcx>(
201 cause: ObligationCause<'tcx>,
202 elaborated_env: ty::ParamEnv<'tcx>,
203 predicates: Vec<ty::Predicate<'tcx>>,
204 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
205 let span = cause.span;
206 // FIXME. We should really... do something with these region
207 // obligations. But this call just continues the older
208 // behavior (i.e., doesn't cause any new bugs), and it would
209 // take some further refactoring to actually solve them. In
210 // particular, we would have to handle implied bounds
211 // properly, and that code is currently largely confined to
212 // regionck (though I made some efforts to extract it
215 // @arielby: In any case, these obligations are checked
216 // by wfcheck anyway, so I'm not sure we have to check
217 // them here too, and we will remove this function when
218 // we move over to lazy normalization *anyway*.
219 let infcx = tcx.infer_ctxt().ignoring_regions().build();
220 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
221 Ok(predicates) => predicates,
223 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
224 return Err(reported);
228 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
230 // We can use the `elaborated_env` here; the region code only
231 // cares about declarations like `'a: 'b`.
232 let outlives_env = OutlivesEnvironment::new(elaborated_env);
234 // FIXME: It's very weird that we ignore region obligations but apparently
235 // still need to use `resolve_regions` as we need the resolved regions in
236 // the normalized predicates.
237 let errors = infcx.resolve_regions(&outlives_env);
238 if !errors.is_empty() {
239 tcx.sess.delay_span_bug(
241 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
245 match infcx.fully_resolve(predicates) {
246 Ok(predicates) => Ok(predicates),
248 // If we encounter a fixup error, it means that some type
249 // variable wound up unconstrained. I actually don't know
250 // if this can happen, and I certainly don't expect it to
251 // happen often, but if it did happen it probably
252 // represents a legitimate failure due to some kind of
253 // unconstrained variable.
255 // @lcnr: Let's still ICE here for now. I want a test case
259 "inference variables in normalized parameter environment: {}",
266 // FIXME: this is gonna need to be removed ...
267 /// Normalizes the parameter environment, reporting errors if they occur.
268 #[instrument(level = "debug", skip(tcx))]
269 pub fn normalize_param_env_or_error<'tcx>(
271 unnormalized_env: ty::ParamEnv<'tcx>,
272 cause: ObligationCause<'tcx>,
273 ) -> ty::ParamEnv<'tcx> {
274 // I'm not wild about reporting errors here; I'd prefer to
275 // have the errors get reported at a defined place (e.g.,
276 // during typeck). Instead I have all parameter
277 // environments, in effect, going through this function
278 // and hence potentially reporting errors. This ensures of
279 // course that we never forget to normalize (the
280 // alternative seemed like it would involve a lot of
281 // manual invocations of this fn -- and then we'd have to
282 // deal with the errors at each of those sites).
284 // In any case, in practice, typeck constructs all the
285 // parameter environments once for every fn as it goes,
286 // and errors will get reported then; so outside of type inference we
287 // can be sure that no errors should occur.
288 let mut predicates: Vec<_> =
289 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
290 .map(|obligation| obligation.predicate)
293 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
295 let elaborated_env = ty::ParamEnv::new(
296 tcx.intern_predicates(&predicates),
297 unnormalized_env.reveal(),
298 unnormalized_env.constness(),
301 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
302 // normalization expects its param-env to be already normalized, which means we have
305 // The way we handle this is by normalizing the param-env inside an unnormalized version
306 // of the param-env, which means that if the param-env contains unnormalized projections,
307 // we'll have some normalization failures. This is unfortunate.
309 // Lazy normalization would basically handle this by treating just the
310 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
312 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
313 // types, so to make the situation less bad, we normalize all the predicates *but*
314 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
315 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
317 // This works fairly well because trait matching does not actually care about param-env
318 // TypeOutlives predicates - these are normally used by regionck.
319 let outlives_predicates: Vec<_> = predicates
320 .drain_filter(|predicate| {
322 predicate.kind().skip_binder(),
323 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
329 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
330 predicates, outlives_predicates
332 let Ok(non_outlives_predicates) = do_normalize_predicates(
338 // An unnormalized env is better than nothing.
339 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
340 return elaborated_env;
343 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
345 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
346 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
347 // predicates here anyway. Keeping them here anyway because it seems safer.
348 let outlives_env: Vec<_> =
349 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
350 let outlives_env = ty::ParamEnv::new(
351 tcx.intern_predicates(&outlives_env),
352 unnormalized_env.reveal(),
353 unnormalized_env.constness(),
355 let Ok(outlives_predicates) = do_normalize_predicates(
361 // An unnormalized env is better than nothing.
362 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
363 return elaborated_env;
365 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
367 let mut predicates = non_outlives_predicates;
368 predicates.extend(outlives_predicates);
369 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
371 tcx.intern_predicates(&predicates),
372 unnormalized_env.reveal(),
373 unnormalized_env.constness(),
377 /// Normalize a type and process all resulting obligations, returning any errors
378 #[instrument(skip_all)]
379 pub fn fully_normalize<'tcx, T>(
380 infcx: &InferCtxt<'tcx>,
381 cause: ObligationCause<'tcx>,
382 param_env: ty::ParamEnv<'tcx>,
384 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
386 T: TypeFoldable<'tcx>,
388 let ocx = ObligationCtxt::new(infcx);
390 let normalized_value = ocx.normalize(&cause, param_env, value);
391 debug!(?normalized_value);
392 debug!("select_all_or_error start");
393 let errors = ocx.select_all_or_error();
394 if !errors.is_empty() {
397 debug!("select_all_or_error complete");
398 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
399 debug!(?resolved_value);
403 /// Process an obligation (and any nested obligations that come from it) to
404 /// completion, returning any errors
405 pub fn fully_solve_obligation<'tcx>(
406 infcx: &InferCtxt<'tcx>,
407 obligation: PredicateObligation<'tcx>,
408 ) -> Vec<FulfillmentError<'tcx>> {
409 fully_solve_obligations(infcx, [obligation])
412 /// Process a set of obligations (and any nested obligations that come from them)
414 pub fn fully_solve_obligations<'tcx>(
415 infcx: &InferCtxt<'tcx>,
416 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
417 ) -> Vec<FulfillmentError<'tcx>> {
418 let ocx = ObligationCtxt::new(infcx);
419 ocx.register_obligations(obligations);
420 ocx.select_all_or_error()
423 /// Process a bound (and any nested obligations that come from it) to completion.
424 /// This is a convenience function for traits that have no generic arguments, such
425 /// as auto traits, and builtin traits like Copy or Sized.
426 pub fn fully_solve_bound<'tcx>(
427 infcx: &InferCtxt<'tcx>,
428 cause: ObligationCause<'tcx>,
429 param_env: ty::ParamEnv<'tcx>,
432 ) -> Vec<FulfillmentError<'tcx>> {
434 let trait_ref = ty::TraitRef { def_id: bound, substs: tcx.mk_substs_trait(ty, []) };
435 let obligation = Obligation {
439 predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
442 fully_solve_obligation(infcx, obligation)
445 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
446 /// returns true, then either normalize encountered an error or one of the predicates did not
447 /// hold. Used when creating vtables to check for unsatisfiable methods.
448 pub fn impossible_predicates<'tcx>(
450 predicates: Vec<ty::Predicate<'tcx>>,
452 debug!("impossible_predicates(predicates={:?})", predicates);
454 let infcx = tcx.infer_ctxt().build();
455 let param_env = ty::ParamEnv::reveal_all();
456 let ocx = ObligationCtxt::new(&infcx);
457 let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
458 for predicate in predicates {
459 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
460 ocx.register_obligation(obligation);
462 let errors = ocx.select_all_or_error();
464 // Clean up after ourselves
465 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
467 let result = !errors.is_empty();
468 debug!("impossible_predicates = {:?}", result);
472 fn subst_and_check_impossible_predicates<'tcx>(
474 key: (DefId, SubstsRef<'tcx>),
476 debug!("subst_and_check_impossible_predicates(key={:?})", key);
478 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
480 // Specifically check trait fulfillment to avoid an error when trying to resolve
482 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
483 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
484 predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
487 predicates.retain(|predicate| !predicate.needs_subst());
488 let result = impossible_predicates(tcx, predicates);
490 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
494 /// Checks whether a trait's method is impossible to call on a given impl.
496 /// This only considers predicates that reference the impl's generics, and not
497 /// those that reference the method's generics.
498 fn is_impossible_method<'tcx>(
500 (impl_def_id, trait_item_def_id): (DefId, DefId),
502 struct ReferencesOnlyParentGenerics<'tcx> {
504 generics: &'tcx ty::Generics,
505 trait_item_def_id: DefId,
507 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
509 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
510 // If this is a parameter from the trait item's own generics, then bail
511 if let ty::Param(param) = t.kind()
512 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
513 && self.tcx.parent(param_def_id) == self.trait_item_def_id
515 return ControlFlow::BREAK;
517 t.super_visit_with(self)
519 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
520 if let ty::ReEarlyBound(param) = r.kind()
521 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
522 && self.tcx.parent(param_def_id) == self.trait_item_def_id
524 return ControlFlow::BREAK;
526 r.super_visit_with(self)
528 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
529 if let ty::ConstKind::Param(param) = ct.kind()
530 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
531 && self.tcx.parent(param_def_id) == self.trait_item_def_id
533 return ControlFlow::BREAK;
535 ct.super_visit_with(self)
539 let generics = tcx.generics_of(trait_item_def_id);
540 let predicates = tcx.predicates_of(trait_item_def_id);
542 tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
543 let param_env = tcx.param_env(impl_def_id);
545 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
546 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
547 if pred.visit_with(&mut visitor).is_continue() {
548 Some(Obligation::new(
550 ObligationCause::dummy_with_span(*span),
552 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
559 let infcx = tcx.infer_ctxt().ignoring_regions().build();
560 for obligation in predicates_for_trait {
561 // Ignore overflow error, to be conservative.
562 if let Ok(result) = infcx.evaluate_obligation(&obligation)
563 && !result.may_apply()
571 #[derive(Clone, Debug)]
572 enum VtblSegment<'tcx> {
574 TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
577 /// Prepare the segments for a vtable
578 fn prepare_vtable_segments<'tcx, T>(
580 trait_ref: ty::PolyTraitRef<'tcx>,
581 mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
583 // The following constraints holds for the final arrangement.
584 // 1. The whole virtual table of the first direct super trait is included as the
585 // the prefix. If this trait doesn't have any super traits, then this step
586 // consists of the dsa metadata.
587 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
588 // other super traits except those already included as part of the first
589 // direct super trait virtual table.
590 // 3. finally, the own methods of this trait.
592 // This has the advantage that trait upcasting to the first direct super trait on each level
593 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
594 // while not using too much extra memory.
596 // For a single inheritance relationship like this,
597 // D --> C --> B --> A
598 // The resulting vtable will consists of these segments:
601 // For a multiple inheritance relationship like this,
604 // The resulting vtable will consists of these segments:
605 // DSA, A, B, B-vptr, C, D
607 // For a diamond inheritance relationship like this,
610 // The resulting vtable will consists of these segments:
611 // DSA, A, B, C, C-vptr, D
613 // For a more complex inheritance relationship like this:
614 // O --> G --> C --> A
622 // The resulting vtable will consists of these segments:
623 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
624 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
627 // emit dsa segment first.
628 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
632 let mut emit_vptr_on_new_entry = false;
633 let mut visited = util::PredicateSet::new(tcx);
634 let predicate = trait_ref.without_const().to_predicate(tcx);
635 let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
636 smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
637 visited.insert(predicate);
639 // the main traversal loop:
640 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
641 // that each node is emitted after all its descendents have been emitted.
642 // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
643 // this is done on the fly.
644 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
645 // stops after it finds a node that has a next-sibling node.
646 // This next-sibling node will used as the starting point of next slice.
649 // For a diamond inheritance relationship like this,
650 // D#1 --> B#0 --> A#0
653 // Starting point 0 stack [D]
654 // Loop run #0: Stack after diving in is [D B A], A is "childless"
655 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
656 // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
657 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
658 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
659 // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
660 // Loop run #1: Stack after exiting out is []. Now the function exits.
663 // dive deeper into the stack, recording the path
665 if let Some((inner_most_trait_ref, _, _)) = stack.last() {
666 let inner_most_trait_ref = *inner_most_trait_ref;
667 let mut direct_super_traits_iter = tcx
668 .super_predicates_of(inner_most_trait_ref.def_id())
671 .filter_map(move |(pred, _)| {
672 pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
675 'diving_in_skip_visited_traits: loop {
676 if let Some(next_super_trait) = direct_super_traits_iter.next() {
677 if visited.insert(next_super_trait.to_predicate(tcx)) {
678 // We're throwing away potential constness of super traits here.
679 // FIXME: handle ~const super traits
680 let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
683 emit_vptr_on_new_entry,
684 Some(direct_super_traits_iter),
686 break 'diving_in_skip_visited_traits;
688 continue 'diving_in_skip_visited_traits;
697 // Other than the left-most path, vptr should be emitted for each trait.
698 emit_vptr_on_new_entry = true;
700 // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
702 if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
703 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
704 trait_ref: *inner_most_trait_ref,
705 emit_vptr: *emit_vptr,
710 'exiting_out_skip_visited_traits: loop {
711 if let Some(siblings) = siblings_opt {
712 if let Some(next_inner_most_trait_ref) = siblings.next() {
713 if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
714 // We're throwing away potential constness of super traits here.
715 // FIXME: handle ~const super traits
716 let next_inner_most_trait_ref =
717 next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
718 *inner_most_trait_ref = next_inner_most_trait_ref;
719 *emit_vptr = emit_vptr_on_new_entry;
722 continue 'exiting_out_skip_visited_traits;
727 continue 'exiting_out;
736 fn dump_vtable_entries<'tcx>(
739 trait_ref: ty::PolyTraitRef<'tcx>,
740 entries: &[VtblEntry<'tcx>],
742 tcx.sess.emit_err(DumpVTableEntries {
745 entries: format!("{:#?}", entries),
749 fn own_existential_vtable_entries<'tcx>(tcx: TyCtxt<'tcx>, trait_def_id: DefId) -> &'tcx [DefId] {
750 let trait_methods = tcx
751 .associated_items(trait_def_id)
752 .in_definition_order()
753 .filter(|item| item.kind == ty::AssocKind::Fn);
754 // Now list each method's DefId (for within its trait).
755 let own_entries = trait_methods.filter_map(move |trait_method| {
756 debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
757 let def_id = trait_method.def_id;
759 // Some methods cannot be called on an object; skip those.
760 if !is_vtable_safe_method(tcx, trait_def_id, &trait_method) {
761 debug!("own_existential_vtable_entry: not vtable safe");
768 tcx.arena.alloc_from_iter(own_entries.into_iter())
771 /// Given a trait `trait_ref`, iterates the vtable entries
772 /// that come from `trait_ref`, including its supertraits.
773 fn vtable_entries<'tcx>(
775 trait_ref: ty::PolyTraitRef<'tcx>,
776 ) -> &'tcx [VtblEntry<'tcx>] {
777 debug!("vtable_entries({:?})", trait_ref);
779 let mut entries = vec![];
781 let vtable_segment_callback = |segment| -> ControlFlow<()> {
783 VtblSegment::MetadataDSA => {
784 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
786 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
787 let existential_trait_ref = trait_ref
788 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
790 // Lookup the shape of vtable for the trait.
791 let own_existential_entries =
792 tcx.own_existential_vtable_entries(existential_trait_ref.def_id());
794 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
795 debug!("vtable_entries: trait_method={:?}", def_id);
797 // The method may have some early-bound lifetimes; add regions for those.
798 let substs = trait_ref.map_bound(|trait_ref| {
799 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
800 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
801 GenericParamDefKind::Type { .. }
802 | GenericParamDefKind::Const { .. } => {
803 trait_ref.substs[param.index as usize]
808 // The trait type may have higher-ranked lifetimes in it;
809 // erase them if they appear, so that we get the type
810 // at some particular call site.
812 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
814 // It's possible that the method relies on where-clauses that
815 // do not hold for this particular set of type parameters.
816 // Note that this method could then never be called, so we
817 // do not want to try and codegen it, in that case (see #23435).
818 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
819 if impossible_predicates(tcx, predicates.predicates) {
820 debug!("vtable_entries: predicates do not hold");
821 return VtblEntry::Vacant;
824 let instance = ty::Instance::resolve_for_vtable(
826 ty::ParamEnv::reveal_all(),
830 .expect("resolution failed during building vtable representation");
831 VtblEntry::Method(instance)
834 entries.extend(own_entries);
837 entries.push(VtblEntry::TraitVPtr(trait_ref));
842 ControlFlow::Continue(())
845 let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
847 if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
848 let sp = tcx.def_span(trait_ref.def_id());
849 dump_vtable_entries(tcx, sp, trait_ref, &entries);
852 tcx.arena.alloc_from_iter(entries.into_iter())
855 /// Find slot base for trait methods within vtable entries of another trait
856 fn vtable_trait_first_method_offset<'tcx>(
859 ty::PolyTraitRef<'tcx>, // trait_to_be_found
860 ty::PolyTraitRef<'tcx>, // trait_owning_vtable
863 let (trait_to_be_found, trait_owning_vtable) = key;
866 let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
868 let vtable_segment_callback = {
869 let mut vtable_base = 0;
873 VtblSegment::MetadataDSA => {
874 vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
876 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
877 if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
878 return ControlFlow::Break(vtable_base);
880 vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
886 ControlFlow::Continue(())
890 if let Some(vtable_base) =
891 prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
895 bug!("Failed to find info for expected trait in vtable");
899 /// Find slot offset for trait vptr within vtable entries of another trait
900 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
903 Ty<'tcx>, // trait object type whose trait owning vtable
904 Ty<'tcx>, // trait object for supertrait
907 let (source, target) = key;
908 assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
909 assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
911 // this has been typecked-before, so diagnostics is not really needed.
912 let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
914 let trait_ref = tcx.mk_trait_ref(unsize_trait_did, [source, target]);
916 match tcx.codegen_select_candidate((ty::ParamEnv::reveal_all(), ty::Binder::dummy(trait_ref))) {
917 Ok(ImplSource::TraitUpcasting(implsrc_traitcasting)) => {
918 implsrc_traitcasting.vtable_vptr_slot
920 otherwise => bug!("expected TraitUpcasting candidate, got {otherwise:?}"),
924 pub fn provide(providers: &mut ty::query::Providers) {
925 object_safety::provide(providers);
926 structural_match::provide(providers);
927 *providers = ty::query::Providers {
928 specialization_graph_of: specialize::specialization_graph_provider,
929 specializes: specialize::specializes,
930 codegen_select_candidate: codegen::codegen_select_candidate,
931 own_existential_vtable_entries,
933 vtable_trait_upcasting_coercion_new_vptr_slot,
934 subst_and_check_impossible_predicates,
935 is_impossible_method,