1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
9 pub mod const_evaluatable;
11 pub mod error_reporting;
18 pub(crate) mod relationships;
25 use crate::infer::outlives::env::OutlivesEnvironment;
26 use crate::infer::{InferCtxt, TyCtxtInferExt};
27 use crate::traits::error_reporting::InferCtxtExt as _;
28 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
29 use rustc_errors::ErrorGuaranteed;
31 use rustc_hir::def_id::DefId;
32 use rustc_hir::lang_items::LangItem;
33 use rustc_infer::traits::TraitEngineExt as _;
34 use rustc_middle::ty::fold::TypeFoldable;
35 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
36 use rustc_middle::ty::visit::TypeVisitable;
37 use rustc_middle::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry};
38 use rustc_span::{sym, Span};
39 use smallvec::SmallVec;
42 use std::ops::ControlFlow;
44 pub use self::FulfillmentErrorCode::*;
45 pub use self::ImplSource::*;
46 pub use self::ObligationCauseCode::*;
47 pub use self::SelectionError::*;
49 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
50 pub use self::coherence::{OrphanCheckErr, OverlapResult};
51 pub use self::engine::{ObligationCtxt, TraitEngineExt};
52 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
53 pub use self::object_safety::astconv_object_safety_violations;
54 pub use self::object_safety::is_vtable_safe_method;
55 pub use self::object_safety::MethodViolationCode;
56 pub use self::object_safety::ObjectSafetyViolation;
57 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
58 pub use self::project::{normalize, normalize_projection_type, normalize_to};
59 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
60 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
61 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
62 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
63 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
64 pub use self::structural_match::{
65 search_for_adt_const_param_violation, search_for_structural_match_violation,
68 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
69 elaborate_trait_ref, elaborate_trait_refs,
71 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
73 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
76 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
77 SupertraitDefIds, Supertraits,
80 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
82 pub use rustc_infer::traits::*;
84 /// Whether to skip the leak check, as part of a future compatibility warning step.
86 /// The "default" for skip-leak-check corresponds to the current
87 /// behavior (do not skip the leak check) -- not the behavior we are
88 /// transitioning into.
89 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
90 pub enum SkipLeakCheck {
97 fn is_yes(self) -> bool {
98 self == SkipLeakCheck::Yes
102 /// The mode that trait queries run in.
103 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
104 pub enum TraitQueryMode {
105 /// Standard/un-canonicalized queries get accurate
106 /// spans etc. passed in and hence can do reasonable
107 /// error reporting on their own.
109 /// Canonicalized queries get dummy spans and hence
110 /// must generally propagate errors to
111 /// pre-canonicalization callsites.
115 /// Creates predicate obligations from the generic bounds.
116 pub fn predicates_for_generics<'tcx>(
117 cause: ObligationCause<'tcx>,
118 param_env: ty::ParamEnv<'tcx>,
119 generic_bounds: ty::InstantiatedPredicates<'tcx>,
120 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
121 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
124 /// Determines whether the type `ty` is known to meet `bound` and
125 /// returns true if so. Returns false if `ty` either does not meet
126 /// `bound` or is not known to meet bound (note that this is
127 /// conservative towards *no impl*, which is the opposite of the
128 /// `evaluate` methods).
129 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
130 infcx: &InferCtxt<'a, 'tcx>,
131 param_env: ty::ParamEnv<'tcx>,
137 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
139 infcx.tcx.def_path_str(def_id)
143 ty::Binder::dummy(ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) });
144 let obligation = Obligation {
146 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
148 predicate: trait_ref.without_const().to_predicate(infcx.tcx),
151 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
153 "type_known_to_meet_ty={:?} bound={} => {:?}",
155 infcx.tcx.def_path_str(def_id),
159 if result && ty.has_infer_types_or_consts() {
160 // Because of inference "guessing", selection can sometimes claim
161 // to succeed while the success requires a guess. To ensure
162 // this function's result remains infallible, we must confirm
163 // that guess. While imperfect, I believe this is sound.
165 // We can use a dummy node-id here because we won't pay any mind
166 // to region obligations that arise (there shouldn't really be any
168 let cause = ObligationCause::misc(span, hir::CRATE_HIR_ID);
170 // The handling of regions in this area of the code is terrible,
171 // see issue #29149. We should be able to improve on this with
173 let errors = fully_solve_bound(infcx, cause, param_env, ty, def_id);
175 // Note: we only assume something is `Copy` if we can
176 // *definitively* show that it implements `Copy`. Otherwise,
177 // assume it is move; linear is always ok.
181 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
183 infcx.tcx.def_path_str(def_id)
190 bound = %infcx.tcx.def_path_str(def_id),
192 "type_known_to_meet_bound_modulo_regions"
202 #[instrument(level = "debug", skip(tcx, elaborated_env))]
203 fn do_normalize_predicates<'tcx>(
205 cause: ObligationCause<'tcx>,
206 elaborated_env: ty::ParamEnv<'tcx>,
207 predicates: Vec<ty::Predicate<'tcx>>,
208 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
209 let span = cause.span;
210 // FIXME. We should really... do something with these region
211 // obligations. But this call just continues the older
212 // behavior (i.e., doesn't cause any new bugs), and it would
213 // take some further refactoring to actually solve them. In
214 // particular, we would have to handle implied bounds
215 // properly, and that code is currently largely confined to
216 // regionck (though I made some efforts to extract it
219 // @arielby: In any case, these obligations are checked
220 // by wfcheck anyway, so I'm not sure we have to check
221 // them here too, and we will remove this function when
222 // we move over to lazy normalization *anyway*.
223 tcx.infer_ctxt().ignoring_regions().enter(|infcx| {
224 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
225 Ok(predicates) => predicates,
227 let reported = infcx.report_fulfillment_errors(&errors, None, false);
228 return Err(reported);
232 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
234 // We can use the `elaborated_env` here; the region code only
235 // cares about declarations like `'a: 'b`.
236 let outlives_env = OutlivesEnvironment::new(elaborated_env);
238 // FIXME: It's very weird that we ignore region obligations but apparently
239 // still need to use `resolve_regions` as we need the resolved regions in
240 // the normalized predicates.
241 let errors = infcx.resolve_regions(&outlives_env);
242 if !errors.is_empty() {
243 tcx.sess.delay_span_bug(
246 "failed region resolution while normalizing {elaborated_env:?}: {errors:?}"
251 match infcx.fully_resolve(predicates) {
252 Ok(predicates) => Ok(predicates),
254 // If we encounter a fixup error, it means that some type
255 // variable wound up unconstrained. I actually don't know
256 // if this can happen, and I certainly don't expect it to
257 // happen often, but if it did happen it probably
258 // represents a legitimate failure due to some kind of
259 // unconstrained variable.
261 // @lcnr: Let's still ICE here for now. I want a test case
265 "inference variables in normalized parameter environment: {}",
273 // FIXME: this is gonna need to be removed ...
274 /// Normalizes the parameter environment, reporting errors if they occur.
275 #[instrument(level = "debug", skip(tcx))]
276 pub fn normalize_param_env_or_error<'tcx>(
278 unnormalized_env: ty::ParamEnv<'tcx>,
279 cause: ObligationCause<'tcx>,
280 ) -> ty::ParamEnv<'tcx> {
281 // I'm not wild about reporting errors here; I'd prefer to
282 // have the errors get reported at a defined place (e.g.,
283 // during typeck). Instead I have all parameter
284 // environments, in effect, going through this function
285 // and hence potentially reporting errors. This ensures of
286 // course that we never forget to normalize (the
287 // alternative seemed like it would involve a lot of
288 // manual invocations of this fn -- and then we'd have to
289 // deal with the errors at each of those sites).
291 // In any case, in practice, typeck constructs all the
292 // parameter environments once for every fn as it goes,
293 // and errors will get reported then; so outside of type inference we
294 // can be sure that no errors should occur.
295 let mut predicates: Vec<_> =
296 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
297 .map(|obligation| obligation.predicate)
300 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
302 let elaborated_env = ty::ParamEnv::new(
303 tcx.intern_predicates(&predicates),
304 unnormalized_env.reveal(),
305 unnormalized_env.constness(),
308 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
309 // normalization expects its param-env to be already normalized, which means we have
312 // The way we handle this is by normalizing the param-env inside an unnormalized version
313 // of the param-env, which means that if the param-env contains unnormalized projections,
314 // we'll have some normalization failures. This is unfortunate.
316 // Lazy normalization would basically handle this by treating just the
317 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
319 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
320 // types, so to make the situation less bad, we normalize all the predicates *but*
321 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
322 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
324 // This works fairly well because trait matching does not actually care about param-env
325 // TypeOutlives predicates - these are normally used by regionck.
326 let outlives_predicates: Vec<_> = predicates
327 .drain_filter(|predicate| {
328 matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..))
333 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
334 predicates, outlives_predicates
336 let Ok(non_outlives_predicates) = do_normalize_predicates(
342 // An unnormalized env is better than nothing.
343 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
344 return elaborated_env;
347 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
349 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
350 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
351 // predicates here anyway. Keeping them here anyway because it seems safer.
352 let outlives_env: Vec<_> =
353 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
354 let outlives_env = ty::ParamEnv::new(
355 tcx.intern_predicates(&outlives_env),
356 unnormalized_env.reveal(),
357 unnormalized_env.constness(),
359 let Ok(outlives_predicates) = do_normalize_predicates(
365 // An unnormalized env is better than nothing.
366 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
367 return elaborated_env;
369 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
371 let mut predicates = non_outlives_predicates;
372 predicates.extend(outlives_predicates);
373 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
375 tcx.intern_predicates(&predicates),
376 unnormalized_env.reveal(),
377 unnormalized_env.constness(),
381 /// Normalize a type and process all resulting obligations, returning any errors
382 pub fn fully_normalize<'a, 'tcx, T>(
383 infcx: &InferCtxt<'a, 'tcx>,
384 cause: ObligationCause<'tcx>,
385 param_env: ty::ParamEnv<'tcx>,
387 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
389 T: TypeFoldable<'tcx>,
391 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
392 let selcx = &mut SelectionContext::new(infcx);
393 let Normalized { value: normalized_value, obligations } =
394 project::normalize(selcx, param_env, cause, value);
396 "fully_normalize: normalized_value={:?} obligations={:?}",
397 normalized_value, obligations
400 let mut fulfill_cx = FulfillmentContext::new();
401 for obligation in obligations {
402 fulfill_cx.register_predicate_obligation(infcx, obligation);
405 debug!("fully_normalize: select_all_or_error start");
406 let errors = fulfill_cx.select_all_or_error(infcx);
407 if !errors.is_empty() {
410 debug!("fully_normalize: select_all_or_error complete");
411 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
412 debug!("fully_normalize: resolved_value={:?}", resolved_value);
416 /// Process an obligation (and any nested obligations that come from it) to
417 /// completion, returning any errors
418 pub fn fully_solve_obligation<'a, 'tcx>(
419 infcx: &InferCtxt<'a, 'tcx>,
420 obligation: PredicateObligation<'tcx>,
421 ) -> Vec<FulfillmentError<'tcx>> {
422 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
423 engine.register_predicate_obligation(infcx, obligation);
424 engine.select_all_or_error(infcx)
427 /// Process a set of obligations (and any nested obligations that come from them)
429 pub fn fully_solve_obligations<'a, 'tcx>(
430 infcx: &InferCtxt<'a, 'tcx>,
431 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
432 ) -> Vec<FulfillmentError<'tcx>> {
433 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
434 engine.register_predicate_obligations(infcx, obligations);
435 engine.select_all_or_error(infcx)
438 /// Process a bound (and any nested obligations that come from it) to completion.
439 /// This is a convenience function for traits that have no generic arguments, such
440 /// as auto traits, and builtin traits like Copy or Sized.
441 pub fn fully_solve_bound<'a, 'tcx>(
442 infcx: &InferCtxt<'a, 'tcx>,
443 cause: ObligationCause<'tcx>,
444 param_env: ty::ParamEnv<'tcx>,
447 ) -> Vec<FulfillmentError<'tcx>> {
448 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
449 engine.register_bound(infcx, param_env, ty, bound, cause);
450 engine.select_all_or_error(infcx)
453 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
454 /// returns true, then either normalize encountered an error or one of the predicates did not
455 /// hold. Used when creating vtables to check for unsatisfiable methods.
456 pub fn impossible_predicates<'tcx>(
458 predicates: Vec<ty::Predicate<'tcx>>,
460 debug!("impossible_predicates(predicates={:?})", predicates);
462 let result = tcx.infer_ctxt().enter(|infcx| {
463 // HACK: Set tainted by errors to gracefully exit in case of overflow.
464 infcx.set_tainted_by_errors();
466 let param_env = ty::ParamEnv::reveal_all();
467 let ocx = ObligationCtxt::new(&infcx);
468 let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);
469 for predicate in predicates {
470 let obligation = Obligation::new(ObligationCause::dummy(), param_env, predicate);
471 ocx.register_obligation(obligation);
473 let errors = ocx.select_all_or_error();
475 // Clean up after ourselves
476 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
480 debug!("impossible_predicates = {:?}", result);
484 fn subst_and_check_impossible_predicates<'tcx>(
486 key: (DefId, SubstsRef<'tcx>),
488 debug!("subst_and_check_impossible_predicates(key={:?})", key);
490 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
492 // Specifically check trait fulfillment to avoid an error when trying to resolve
494 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
495 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
496 predicates.push(ty::Binder::dummy(trait_ref).to_poly_trait_predicate().to_predicate(tcx));
499 predicates.retain(|predicate| !predicate.needs_subst());
500 let result = impossible_predicates(tcx, predicates);
502 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
506 #[derive(Clone, Debug)]
507 enum VtblSegment<'tcx> {
509 TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
512 /// Prepare the segments for a vtable
513 fn prepare_vtable_segments<'tcx, T>(
515 trait_ref: ty::PolyTraitRef<'tcx>,
516 mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
518 // The following constraints holds for the final arrangement.
519 // 1. The whole virtual table of the first direct super trait is included as the
520 // the prefix. If this trait doesn't have any super traits, then this step
521 // consists of the dsa metadata.
522 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
523 // other super traits except those already included as part of the first
524 // direct super trait virtual table.
525 // 3. finally, the own methods of this trait.
527 // This has the advantage that trait upcasting to the first direct super trait on each level
528 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
529 // while not using too much extra memory.
531 // For a single inheritance relationship like this,
532 // D --> C --> B --> A
533 // The resulting vtable will consists of these segments:
536 // For a multiple inheritance relationship like this,
539 // The resulting vtable will consists of these segments:
540 // DSA, A, B, B-vptr, C, D
542 // For a diamond inheritance relationship like this,
545 // The resulting vtable will consists of these segments:
546 // DSA, A, B, C, C-vptr, D
548 // For a more complex inheritance relationship like this:
549 // O --> G --> C --> A
557 // The resulting vtable will consists of these segments:
558 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
559 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
562 // emit dsa segment first.
563 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
567 let mut emit_vptr_on_new_entry = false;
568 let mut visited = util::PredicateSet::new(tcx);
569 let predicate = trait_ref.without_const().to_predicate(tcx);
570 let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
571 smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
572 visited.insert(predicate);
574 // the main traversal loop:
575 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
576 // that each node is emitted after all its descendents have been emitted.
577 // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
578 // this is done on the fly.
579 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
580 // stops after it finds a node that has a next-sibling node.
581 // This next-sibling node will used as the starting point of next slice.
584 // For a diamond inheritance relationship like this,
585 // D#1 --> B#0 --> A#0
588 // Starting point 0 stack [D]
589 // Loop run #0: Stack after diving in is [D B A], A is "childless"
590 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
591 // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
592 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
593 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
594 // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
595 // Loop run #1: Stack after exiting out is []. Now the function exits.
598 // dive deeper into the stack, recording the path
600 if let Some((inner_most_trait_ref, _, _)) = stack.last() {
601 let inner_most_trait_ref = *inner_most_trait_ref;
602 let mut direct_super_traits_iter = tcx
603 .super_predicates_of(inner_most_trait_ref.def_id())
606 .filter_map(move |(pred, _)| {
607 pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
610 'diving_in_skip_visited_traits: loop {
611 if let Some(next_super_trait) = direct_super_traits_iter.next() {
612 if visited.insert(next_super_trait.to_predicate(tcx)) {
613 // We're throwing away potential constness of super traits here.
614 // FIXME: handle ~const super traits
615 let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
618 emit_vptr_on_new_entry,
619 Some(direct_super_traits_iter),
621 break 'diving_in_skip_visited_traits;
623 continue 'diving_in_skip_visited_traits;
632 // Other than the left-most path, vptr should be emitted for each trait.
633 emit_vptr_on_new_entry = true;
635 // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
637 if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
638 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
639 trait_ref: *inner_most_trait_ref,
640 emit_vptr: *emit_vptr,
645 'exiting_out_skip_visited_traits: loop {
646 if let Some(siblings) = siblings_opt {
647 if let Some(next_inner_most_trait_ref) = siblings.next() {
648 if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
649 // We're throwing away potential constness of super traits here.
650 // FIXME: handle ~const super traits
651 let next_inner_most_trait_ref =
652 next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
653 *inner_most_trait_ref = next_inner_most_trait_ref;
654 *emit_vptr = emit_vptr_on_new_entry;
657 continue 'exiting_out_skip_visited_traits;
662 continue 'exiting_out;
671 fn dump_vtable_entries<'tcx>(
674 trait_ref: ty::PolyTraitRef<'tcx>,
675 entries: &[VtblEntry<'tcx>],
677 let msg = format!("vtable entries for `{}`: {:#?}", trait_ref, entries);
678 tcx.sess.struct_span_err(sp, &msg).emit();
681 fn own_existential_vtable_entries<'tcx>(
683 trait_ref: ty::PolyExistentialTraitRef<'tcx>,
685 let trait_methods = tcx
686 .associated_items(trait_ref.def_id())
687 .in_definition_order()
688 .filter(|item| item.kind == ty::AssocKind::Fn);
689 // Now list each method's DefId (for within its trait).
690 let own_entries = trait_methods.filter_map(move |trait_method| {
691 debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
692 let def_id = trait_method.def_id;
694 // Some methods cannot be called on an object; skip those.
695 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
696 debug!("own_existential_vtable_entry: not vtable safe");
703 tcx.arena.alloc_from_iter(own_entries.into_iter())
706 /// Given a trait `trait_ref`, iterates the vtable entries
707 /// that come from `trait_ref`, including its supertraits.
708 fn vtable_entries<'tcx>(
710 trait_ref: ty::PolyTraitRef<'tcx>,
711 ) -> &'tcx [VtblEntry<'tcx>] {
712 debug!("vtable_entries({:?})", trait_ref);
714 let mut entries = vec![];
716 let vtable_segment_callback = |segment| -> ControlFlow<()> {
718 VtblSegment::MetadataDSA => {
719 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
721 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
722 let existential_trait_ref = trait_ref
723 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
725 // Lookup the shape of vtable for the trait.
726 let own_existential_entries =
727 tcx.own_existential_vtable_entries(existential_trait_ref);
729 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
730 debug!("vtable_entries: trait_method={:?}", def_id);
732 // The method may have some early-bound lifetimes; add regions for those.
733 let substs = trait_ref.map_bound(|trait_ref| {
734 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
735 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
736 GenericParamDefKind::Type { .. }
737 | GenericParamDefKind::Const { .. } => {
738 trait_ref.substs[param.index as usize]
743 // The trait type may have higher-ranked lifetimes in it;
744 // erase them if they appear, so that we get the type
745 // at some particular call site.
747 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
749 // It's possible that the method relies on where-clauses that
750 // do not hold for this particular set of type parameters.
751 // Note that this method could then never be called, so we
752 // do not want to try and codegen it, in that case (see #23435).
753 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
754 if impossible_predicates(tcx, predicates.predicates) {
755 debug!("vtable_entries: predicates do not hold");
756 return VtblEntry::Vacant;
759 let instance = ty::Instance::resolve_for_vtable(
761 ty::ParamEnv::reveal_all(),
765 .expect("resolution failed during building vtable representation");
766 VtblEntry::Method(instance)
769 entries.extend(own_entries);
772 entries.push(VtblEntry::TraitVPtr(trait_ref));
777 ControlFlow::Continue(())
780 let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
782 if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
783 let sp = tcx.def_span(trait_ref.def_id());
784 dump_vtable_entries(tcx, sp, trait_ref, &entries);
787 tcx.arena.alloc_from_iter(entries.into_iter())
790 /// Find slot base for trait methods within vtable entries of another trait
791 fn vtable_trait_first_method_offset<'tcx>(
794 ty::PolyTraitRef<'tcx>, // trait_to_be_found
795 ty::PolyTraitRef<'tcx>, // trait_owning_vtable
798 let (trait_to_be_found, trait_owning_vtable) = key;
801 let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
803 let vtable_segment_callback = {
804 let mut vtable_base = 0;
808 VtblSegment::MetadataDSA => {
809 vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
811 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
812 if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
813 return ControlFlow::Break(vtable_base);
815 vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
821 ControlFlow::Continue(())
825 if let Some(vtable_base) =
826 prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
830 bug!("Failed to find info for expected trait in vtable");
834 /// Find slot offset for trait vptr within vtable entries of another trait
835 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
838 Ty<'tcx>, // trait object type whose trait owning vtable
839 Ty<'tcx>, // trait object for supertrait
842 let (source, target) = key;
843 assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
844 assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
846 // this has been typecked-before, so diagnostics is not really needed.
847 let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
849 let trait_ref = ty::TraitRef {
850 def_id: unsize_trait_did,
851 substs: tcx.mk_substs_trait(source, &[target.into()]),
853 let obligation = Obligation::new(
854 ObligationCause::dummy(),
855 ty::ParamEnv::reveal_all(),
856 ty::Binder::dummy(ty::TraitPredicate {
858 constness: ty::BoundConstness::NotConst,
859 polarity: ty::ImplPolarity::Positive,
863 let implsrc = tcx.infer_ctxt().enter(|infcx| {
864 let mut selcx = SelectionContext::new(&infcx);
865 selcx.select(&obligation).unwrap()
868 let Some(ImplSource::TraitUpcasting(implsrc_traitcasting)) = implsrc else {
872 implsrc_traitcasting.vtable_vptr_slot
875 pub fn provide(providers: &mut ty::query::Providers) {
876 object_safety::provide(providers);
877 structural_match::provide(providers);
878 *providers = ty::query::Providers {
879 specialization_graph_of: specialize::specialization_graph_provider,
880 specializes: specialize::specializes,
881 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
882 own_existential_vtable_entries,
884 vtable_trait_upcasting_coercion_new_vptr_slot,
885 subst_and_check_impossible_predicates,
886 try_unify_abstract_consts: |tcx, param_env_and| {
887 let (param_env, (a, b)) = param_env_and.into_parts();
888 const_evaluatable::try_unify_abstract_consts(tcx, (a, b), param_env)