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, RegionckMode, TyCtxtInferExt};
27 use crate::traits::error_reporting::InferCtxtExt as _;
28 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
29 use rustc_errors::ErrorReported;
31 use rustc_hir::def_id::DefId;
32 use rustc_hir::lang_items::LangItem;
33 use rustc_middle::ty::fold::TypeFoldable;
34 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
35 use rustc_middle::ty::{
36 self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry, WithConstness,
37 COMMON_VTABLE_ENTRIES,
39 use rustc_span::{sym, Span};
40 use smallvec::SmallVec;
43 use std::ops::ControlFlow;
45 pub use self::FulfillmentErrorCode::*;
46 pub use self::ImplSource::*;
47 pub use self::ObligationCauseCode::*;
48 pub use self::SelectionError::*;
50 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
51 pub use self::coherence::{OrphanCheckErr, OverlapResult};
52 pub use self::engine::TraitEngineExt;
53 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
54 pub use self::object_safety::astconv_object_safety_violations;
55 pub use self::object_safety::is_vtable_safe_method;
56 pub use self::object_safety::MethodViolationCode;
57 pub use self::object_safety::ObjectSafetyViolation;
58 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
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::search_for_structural_match_violation;
66 pub use self::structural_match::NonStructuralMatchTy;
68 elaborate_obligations, elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs,
70 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
72 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
75 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
76 SupertraitDefIds, Supertraits,
79 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
81 pub use rustc_infer::traits::*;
83 /// Whether to skip the leak check, as part of a future compatibility warning step.
84 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
85 pub enum SkipLeakCheck {
91 fn is_yes(self) -> bool {
92 self == SkipLeakCheck::Yes
96 /// The "default" for skip-leak-check corresponds to the current
97 /// behavior (do not skip the leak check) -- not the behavior we are
98 /// transitioning into.
99 impl Default for SkipLeakCheck {
100 fn default() -> Self {
105 /// The mode that trait queries run in.
106 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
107 pub enum TraitQueryMode {
108 /// Standard/un-canonicalized queries get accurate
109 /// spans etc. passed in and hence can do reasonable
110 /// error reporting on their own.
112 /// Canonicalized queries get dummy spans and hence
113 /// must generally propagate errors to
114 /// pre-canonicalization callsites.
118 /// Creates predicate obligations from the generic bounds.
119 pub fn predicates_for_generics<'tcx>(
120 cause: ObligationCause<'tcx>,
121 param_env: ty::ParamEnv<'tcx>,
122 generic_bounds: ty::InstantiatedPredicates<'tcx>,
123 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
124 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
127 /// Determines whether the type `ty` is known to meet `bound` and
128 /// returns true if so. Returns false if `ty` either does not meet
129 /// `bound` or is not known to meet bound (note that this is
130 /// conservative towards *no impl*, which is the opposite of the
131 /// `evaluate` methods).
132 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
133 infcx: &InferCtxt<'a, 'tcx>,
134 param_env: ty::ParamEnv<'tcx>,
140 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
142 infcx.tcx.def_path_str(def_id)
146 ty::Binder::dummy(ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) });
147 let obligation = Obligation {
149 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
151 predicate: trait_ref.without_const().to_predicate(infcx.tcx),
154 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
156 "type_known_to_meet_ty={:?} bound={} => {:?}",
158 infcx.tcx.def_path_str(def_id),
162 if result && ty.has_infer_types_or_consts() {
163 // Because of inference "guessing", selection can sometimes claim
164 // to succeed while the success requires a guess. To ensure
165 // this function's result remains infallible, we must confirm
166 // that guess. While imperfect, I believe this is sound.
168 // The handling of regions in this area of the code is terrible,
169 // see issue #29149. We should be able to improve on this with
171 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
173 // We can use a dummy node-id here because we won't pay any mind
174 // to region obligations that arise (there shouldn't really be any
176 let cause = ObligationCause::misc(span, hir::CRATE_HIR_ID);
178 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
180 // Note: we only assume something is `Copy` if we can
181 // *definitively* show that it implements `Copy`. Otherwise,
182 // assume it is move; linear is always ok.
183 match fulfill_cx.select_all_or_error(infcx) {
186 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
188 infcx.tcx.def_path_str(def_id)
194 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
196 infcx.tcx.def_path_str(def_id),
207 fn do_normalize_predicates<'tcx>(
209 region_context: DefId,
210 cause: ObligationCause<'tcx>,
211 elaborated_env: ty::ParamEnv<'tcx>,
212 predicates: Vec<ty::Predicate<'tcx>>,
213 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
215 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
216 predicates, region_context, cause,
218 let span = cause.span;
219 tcx.infer_ctxt().enter(|infcx| {
220 // FIXME. We should really... do something with these region
221 // obligations. But this call just continues the older
222 // behavior (i.e., doesn't cause any new bugs), and it would
223 // take some further refactoring to actually solve them. In
224 // particular, we would have to handle implied bounds
225 // properly, and that code is currently largely confined to
226 // regionck (though I made some efforts to extract it
229 // @arielby: In any case, these obligations are checked
230 // by wfcheck anyway, so I'm not sure we have to check
231 // them here too, and we will remove this function when
232 // we move over to lazy normalization *anyway*.
233 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
235 match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, predicates) {
236 Ok(predicates) => predicates,
238 infcx.report_fulfillment_errors(&errors, None, false);
239 return Err(ErrorReported);
243 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
245 // We can use the `elaborated_env` here; the region code only
246 // cares about declarations like `'a: 'b`.
247 let outlives_env = OutlivesEnvironment::new(elaborated_env);
249 infcx.resolve_regions_and_report_errors(
252 RegionckMode::default(),
255 let predicates = match infcx.fully_resolve(predicates) {
256 Ok(predicates) => predicates,
258 // If we encounter a fixup error, it means that some type
259 // variable wound up unconstrained. I actually don't know
260 // if this can happen, and I certainly don't expect it to
261 // happen often, but if it did happen it probably
262 // represents a legitimate failure due to some kind of
263 // unconstrained variable, and it seems better not to ICE,
264 // all things considered.
265 tcx.sess.span_err(span, &fixup_err.to_string());
266 return Err(ErrorReported);
269 if predicates.needs_infer() {
270 tcx.sess.delay_span_bug(span, "encountered inference variables after `fully_resolve`");
278 // FIXME: this is gonna need to be removed ...
279 /// Normalizes the parameter environment, reporting errors if they occur.
280 pub fn normalize_param_env_or_error<'tcx>(
282 region_context: DefId,
283 unnormalized_env: ty::ParamEnv<'tcx>,
284 cause: ObligationCause<'tcx>,
285 ) -> ty::ParamEnv<'tcx> {
286 // I'm not wild about reporting errors here; I'd prefer to
287 // have the errors get reported at a defined place (e.g.,
288 // during typeck). Instead I have all parameter
289 // environments, in effect, going through this function
290 // and hence potentially reporting errors. This ensures of
291 // course that we never forget to normalize (the
292 // alternative seemed like it would involve a lot of
293 // manual invocations of this fn -- and then we'd have to
294 // deal with the errors at each of those sites).
296 // In any case, in practice, typeck constructs all the
297 // parameter environments once for every fn as it goes,
298 // and errors will get reported then; so after typeck we
299 // can be sure that no errors should occur.
302 "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
303 region_context, unnormalized_env, cause
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);
314 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal());
316 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
317 // normalization expects its param-env to be already normalized, which means we have
320 // The way we handle this is by normalizing the param-env inside an unnormalized version
321 // of the param-env, which means that if the param-env contains unnormalized projections,
322 // we'll have some normalization failures. This is unfortunate.
324 // Lazy normalization would basically handle this by treating just the
325 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
327 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
328 // types, so to make the situation less bad, we normalize all the predicates *but*
329 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
330 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
332 // This works fairly well because trait matching does not actually care about param-env
333 // TypeOutlives predicates - these are normally used by regionck.
334 let outlives_predicates: Vec<_> = predicates
335 .drain_filter(|predicate| {
336 matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..))
341 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
342 predicates, outlives_predicates
344 let non_outlives_predicates = match do_normalize_predicates(
351 Ok(predicates) => predicates,
352 // An unnormalized env is better than nothing.
353 Err(ErrorReported) => {
354 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
355 return elaborated_env;
359 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
361 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
362 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
363 // predicates here anyway. Keeping them here anyway because it seems safer.
364 let outlives_env: Vec<_> =
365 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
367 ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal());
368 let outlives_predicates = match do_normalize_predicates(
375 Ok(predicates) => predicates,
376 // An unnormalized env is better than nothing.
377 Err(ErrorReported) => {
378 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
379 return elaborated_env;
382 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
384 let mut predicates = non_outlives_predicates;
385 predicates.extend(outlives_predicates);
386 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
387 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal())
390 pub fn fully_normalize<'a, 'tcx, T>(
391 infcx: &InferCtxt<'a, 'tcx>,
392 mut fulfill_cx: FulfillmentContext<'tcx>,
393 cause: ObligationCause<'tcx>,
394 param_env: ty::ParamEnv<'tcx>,
396 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
398 T: TypeFoldable<'tcx>,
400 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
401 let selcx = &mut SelectionContext::new(infcx);
402 let Normalized { value: normalized_value, obligations } =
403 project::normalize(selcx, param_env, cause, value);
405 "fully_normalize: normalized_value={:?} obligations={:?}",
406 normalized_value, obligations
408 for obligation in obligations {
409 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
412 debug!("fully_normalize: select_all_or_error start");
413 fulfill_cx.select_all_or_error(infcx)?;
414 debug!("fully_normalize: select_all_or_error complete");
415 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
416 debug!("fully_normalize: resolved_value={:?}", resolved_value);
420 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
421 /// returns true, then either normalize encountered an error or one of the predicates did not
422 /// hold. Used when creating vtables to check for unsatisfiable methods.
423 pub fn impossible_predicates<'tcx>(
425 predicates: Vec<ty::Predicate<'tcx>>,
427 debug!("impossible_predicates(predicates={:?})", predicates);
429 let result = tcx.infer_ctxt().enter(|infcx| {
430 let param_env = ty::ParamEnv::reveal_all();
431 let mut selcx = SelectionContext::new(&infcx);
432 let mut fulfill_cx = FulfillmentContext::new();
433 let cause = ObligationCause::dummy();
434 let Normalized { value: predicates, obligations } =
435 normalize(&mut selcx, param_env, cause.clone(), predicates);
436 for obligation in obligations {
437 fulfill_cx.register_predicate_obligation(&infcx, obligation);
439 for predicate in predicates {
440 let obligation = Obligation::new(cause.clone(), param_env, predicate);
441 fulfill_cx.register_predicate_obligation(&infcx, obligation);
444 fulfill_cx.select_all_or_error(&infcx).is_err()
446 debug!("impossible_predicates = {:?}", result);
450 fn subst_and_check_impossible_predicates<'tcx>(
452 key: (DefId, SubstsRef<'tcx>),
454 debug!("subst_and_check_impossible_predicates(key={:?})", key);
456 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
457 predicates.retain(|predicate| !predicate.definitely_needs_subst(tcx));
458 let result = impossible_predicates(tcx, predicates);
460 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
464 #[derive(Clone, Debug)]
465 enum VtblSegment<'tcx> {
467 TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
470 /// Prepare the segments for a vtable
471 fn prepare_vtable_segments<'tcx, T>(
473 trait_ref: ty::PolyTraitRef<'tcx>,
474 mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
476 // The following constraints holds for the final arrangement.
477 // 1. The whole virtual table of the first direct super trait is included as the
478 // the prefix. If this trait doesn't have any super traits, then this step
479 // consists of the dsa metadata.
480 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
481 // other super traits except those already included as part of the first
482 // direct super trait virtual table.
483 // 3. finally, the own methods of this trait.
485 // This has the advantage that trait upcasting to the first direct super trait on each level
486 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
487 // while not using too much extra memory.
489 // For a single inheritance relationship like this,
490 // D --> C --> B --> A
491 // The resulting vtable will consists of these segments:
494 // For a multiple inheritance relationship like this,
497 // The resulting vtable will consists of these segments:
498 // DSA, A, B, B-vptr, C, D
500 // For a diamond inheritance relationship like this,
503 // The resulting vtable will consists of these segments:
504 // DSA, A, B, C, C-vptr, D
506 // For a more complex inheritance relationship like this:
507 // O --> G --> C --> A
515 // The resulting vtable will consists of these segments:
516 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
517 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
520 // emit dsa segment first.
521 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
525 let mut emit_vptr_on_new_entry = false;
526 let mut visited = util::PredicateSet::new(tcx);
527 let predicate = trait_ref.without_const().to_predicate(tcx);
528 let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
529 smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
530 visited.insert(predicate);
532 // the main traversal loop:
533 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
534 // that each node is emited after all its descendents have been emitted.
535 // so we convert the directed graph into a tree by skipping all previously visted nodes using a visited set.
536 // this is done on the fly.
537 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
538 // stops after it finds a node that has a next-sibling node.
539 // This next-sibling node will used as the starting point of next slice.
542 // For a diamond inheritance relationship like this,
543 // D#1 --> B#0 --> A#0
546 // Starting point 0 stack [D]
547 // Loop run #0: Stack after diving in is [D B A], A is "childless"
548 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
549 // Loop run #0: Emiting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
550 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
551 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
552 // Loop run #1: Emiting the slice [D C] (in reverse order). No one has a next-sibling node.
553 // Loop run #1: Stack after exiting out is []. Now the function exits.
556 // dive deeper into the stack, recording the path
558 if let Some((inner_most_trait_ref, _, _)) = stack.last() {
559 let inner_most_trait_ref = *inner_most_trait_ref;
560 let mut direct_super_traits_iter = tcx
561 .super_predicates_of(inner_most_trait_ref.def_id())
564 .filter_map(move |(pred, _)| {
565 pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_ref()
568 'diving_in_skip_visited_traits: loop {
569 if let Some(next_super_trait) = direct_super_traits_iter.next() {
570 if visited.insert(next_super_trait.to_predicate(tcx)) {
572 next_super_trait.value,
573 emit_vptr_on_new_entry,
574 Some(direct_super_traits_iter),
576 break 'diving_in_skip_visited_traits;
578 continue 'diving_in_skip_visited_traits;
587 // Other than the left-most path, vptr should be emitted for each trait.
588 emit_vptr_on_new_entry = true;
590 // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
592 if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
593 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
594 trait_ref: *inner_most_trait_ref,
595 emit_vptr: *emit_vptr,
600 'exiting_out_skip_visited_traits: loop {
601 if let Some(siblings) = siblings_opt {
602 if let Some(next_inner_most_trait_ref) = siblings.next() {
603 if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
604 *inner_most_trait_ref = next_inner_most_trait_ref.value;
605 *emit_vptr = emit_vptr_on_new_entry;
608 continue 'exiting_out_skip_visited_traits;
613 continue 'exiting_out;
622 fn dump_vtable_entries<'tcx>(
625 trait_ref: ty::PolyTraitRef<'tcx>,
626 entries: &[VtblEntry<'tcx>],
628 let msg = format!("vtable entries for `{}`: {:#?}", trait_ref, entries);
629 tcx.sess.struct_span_err(sp, &msg).emit();
632 fn own_existential_vtable_entries<'tcx>(
634 trait_ref: ty::PolyExistentialTraitRef<'tcx>,
636 let trait_methods = tcx
637 .associated_items(trait_ref.def_id())
638 .in_definition_order()
639 .filter(|item| item.kind == ty::AssocKind::Fn);
640 // Now list each method's DefId (for within its trait).
641 let own_entries = trait_methods.filter_map(move |trait_method| {
642 debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
643 let def_id = trait_method.def_id;
645 // Some methods cannot be called on an object; skip those.
646 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
647 debug!("own_existential_vtable_entry: not vtable safe");
654 tcx.arena.alloc_from_iter(own_entries.into_iter())
657 /// Given a trait `trait_ref`, iterates the vtable entries
658 /// that come from `trait_ref`, including its supertraits.
659 fn vtable_entries<'tcx>(
661 trait_ref: ty::PolyTraitRef<'tcx>,
662 ) -> &'tcx [VtblEntry<'tcx>] {
663 debug!("vtable_entries({:?})", trait_ref);
665 let mut entries = vec![];
667 let vtable_segment_callback = |segment| -> ControlFlow<()> {
669 VtblSegment::MetadataDSA => {
670 entries.extend(COMMON_VTABLE_ENTRIES);
672 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
673 let existential_trait_ref = trait_ref
674 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
676 // Lookup the shape of vtable for the trait.
677 let own_existential_entries =
678 tcx.own_existential_vtable_entries(existential_trait_ref);
680 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
681 debug!("vtable_entries: trait_method={:?}", def_id);
683 // The method may have some early-bound lifetimes; add regions for those.
684 let substs = trait_ref.map_bound(|trait_ref| {
685 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
686 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
687 GenericParamDefKind::Type { .. }
688 | GenericParamDefKind::Const { .. } => {
689 trait_ref.substs[param.index as usize]
694 // The trait type may have higher-ranked lifetimes in it;
695 // erase them if they appear, so that we get the type
696 // at some particular call site.
698 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
700 // It's possible that the method relies on where-clauses that
701 // do not hold for this particular set of type parameters.
702 // Note that this method could then never be called, so we
703 // do not want to try and codegen it, in that case (see #23435).
704 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
705 if impossible_predicates(tcx, predicates.predicates) {
706 debug!("vtable_entries: predicates do not hold");
707 return VtblEntry::Vacant;
710 let instance = ty::Instance::resolve_for_vtable(
712 ty::ParamEnv::reveal_all(),
716 .expect("resolution failed during building vtable representation");
717 VtblEntry::Method(instance)
720 entries.extend(own_entries);
723 entries.push(VtblEntry::TraitVPtr(trait_ref));
728 ControlFlow::Continue(())
731 let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
733 if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
734 let sp = tcx.def_span(trait_ref.def_id());
735 dump_vtable_entries(tcx, sp, trait_ref, &entries);
738 tcx.arena.alloc_from_iter(entries.into_iter())
741 /// Find slot base for trait methods within vtable entries of another trait
742 fn vtable_trait_first_method_offset<'tcx>(
745 ty::PolyTraitRef<'tcx>, // trait_to_be_found
746 ty::PolyTraitRef<'tcx>, // trait_owning_vtable
749 let (trait_to_be_found, trait_owning_vtable) = key;
752 let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
754 let vtable_segment_callback = {
755 let mut vtable_base = 0;
759 VtblSegment::MetadataDSA => {
760 vtable_base += COMMON_VTABLE_ENTRIES.len();
762 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
763 if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
764 return ControlFlow::Break(vtable_base);
766 vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
772 ControlFlow::Continue(())
776 if let Some(vtable_base) =
777 prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
781 bug!("Failed to find info for expected trait in vtable");
785 /// Find slot offset for trait vptr within vtable entries of another trait
786 pub fn vtable_trait_upcasting_coercion_new_vptr_slot(
789 Ty<'tcx>, // trait object type whose trait owning vtable
790 Ty<'tcx>, // trait object for supertrait
793 let (source, target) = key;
794 assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
795 assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
797 // this has been typecked-before, so diagnostics is not really needed.
798 let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
800 let trait_ref = ty::TraitRef {
801 def_id: unsize_trait_did,
802 substs: tcx.mk_substs_trait(source, &[target.into()]),
804 let obligation = Obligation::new(
805 ObligationCause::dummy(),
806 ty::ParamEnv::reveal_all(),
807 ty::Binder::dummy(ty::TraitPredicate {
809 constness: ty::BoundConstness::NotConst,
810 polarity: ty::ImplPolarity::Positive,
814 let implsrc = tcx.infer_ctxt().enter(|infcx| {
815 let mut selcx = SelectionContext::new(&infcx);
816 selcx.select(&obligation).unwrap()
819 let implsrc_traitcasting = match implsrc {
820 Some(ImplSource::TraitUpcasting(data)) => data,
824 implsrc_traitcasting.vtable_vptr_slot
827 pub fn provide(providers: &mut ty::query::Providers) {
828 object_safety::provide(providers);
829 structural_match::provide(providers);
830 *providers = ty::query::Providers {
831 specialization_graph_of: specialize::specialization_graph_provider,
832 specializes: specialize::specializes,
833 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
834 own_existential_vtable_entries,
836 vtable_trait_upcasting_coercion_new_vptr_slot,
837 subst_and_check_impossible_predicates,
838 thir_abstract_const: |tcx, def_id| {
839 let def_id = def_id.expect_local();
840 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
841 tcx.thir_abstract_const_of_const_arg(def)
843 const_evaluatable::thir_abstract_const(tcx, ty::WithOptConstParam::unknown(def_id))
846 thir_abstract_const_of_const_arg: |tcx, (did, param_did)| {
847 const_evaluatable::thir_abstract_const(
849 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
852 try_unify_abstract_consts: const_evaluatable::try_unify_abstract_consts,