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::{
38 self, DefIdTree, GenericParamDefKind, Subst, ToPredicate, Ty, TyCtxt, TypeSuperVisitable,
41 use rustc_span::{sym, Span};
42 use smallvec::SmallVec;
45 use std::ops::ControlFlow;
47 pub use self::FulfillmentErrorCode::*;
48 pub use self::ImplSource::*;
49 pub use self::ObligationCauseCode::*;
50 pub use self::SelectionError::*;
52 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
53 pub use self::coherence::{OrphanCheckErr, OverlapResult};
54 pub use self::engine::{ObligationCtxt, TraitEngineExt};
55 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
56 pub use self::object_safety::astconv_object_safety_violations;
57 pub use self::object_safety::is_vtable_safe_method;
58 pub use self::object_safety::MethodViolationCode;
59 pub use self::object_safety::ObjectSafetyViolation;
60 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
61 pub use self::project::{normalize, normalize_projection_type, normalize_to};
62 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
63 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
64 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
65 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
66 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
67 pub use self::structural_match::{
68 search_for_adt_const_param_violation, search_for_structural_match_violation,
71 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
72 elaborate_trait_ref, elaborate_trait_refs,
74 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
76 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
79 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
80 SupertraitDefIds, Supertraits,
83 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
85 pub use rustc_infer::traits::*;
87 /// Whether to skip the leak check, as part of a future compatibility warning step.
89 /// The "default" for skip-leak-check corresponds to the current
90 /// behavior (do not skip the leak check) -- not the behavior we are
91 /// transitioning into.
92 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
93 pub enum SkipLeakCheck {
100 fn is_yes(self) -> bool {
101 self == SkipLeakCheck::Yes
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 // We can use a dummy node-id here because we won't pay any mind
169 // to region obligations that arise (there shouldn't really be any
171 let cause = ObligationCause::misc(span, hir::CRATE_HIR_ID);
173 // The handling of regions in this area of the code is terrible,
174 // see issue #29149. We should be able to improve on this with
176 let errors = fully_solve_bound(infcx, cause, param_env, ty, def_id);
178 // Note: we only assume something is `Copy` if we can
179 // *definitively* show that it implements `Copy`. Otherwise,
180 // assume it is move; linear is always ok.
184 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
186 infcx.tcx.def_path_str(def_id)
193 bound = %infcx.tcx.def_path_str(def_id),
195 "type_known_to_meet_bound_modulo_regions"
205 #[instrument(level = "debug", skip(tcx, elaborated_env))]
206 fn do_normalize_predicates<'tcx>(
208 cause: ObligationCause<'tcx>,
209 elaborated_env: ty::ParamEnv<'tcx>,
210 predicates: Vec<ty::Predicate<'tcx>>,
211 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
212 let span = cause.span;
213 // FIXME. We should really... do something with these region
214 // obligations. But this call just continues the older
215 // behavior (i.e., doesn't cause any new bugs), and it would
216 // take some further refactoring to actually solve them. In
217 // particular, we would have to handle implied bounds
218 // properly, and that code is currently largely confined to
219 // regionck (though I made some efforts to extract it
222 // @arielby: In any case, these obligations are checked
223 // by wfcheck anyway, so I'm not sure we have to check
224 // them here too, and we will remove this function when
225 // we move over to lazy normalization *anyway*.
226 tcx.infer_ctxt().ignoring_regions().enter(|infcx| {
227 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
228 Ok(predicates) => predicates,
230 let reported = infcx.report_fulfillment_errors(&errors, None, false);
231 return Err(reported);
235 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
237 // We can use the `elaborated_env` here; the region code only
238 // cares about declarations like `'a: 'b`.
239 let outlives_env = OutlivesEnvironment::new(elaborated_env);
241 // FIXME: It's very weird that we ignore region obligations but apparently
242 // still need to use `resolve_regions` as we need the resolved regions in
243 // the normalized predicates.
244 let errors = infcx.resolve_regions(&outlives_env);
245 if !errors.is_empty() {
246 tcx.sess.delay_span_bug(
249 "failed region resolution while normalizing {elaborated_env:?}: {errors:?}"
254 match infcx.fully_resolve(predicates) {
255 Ok(predicates) => Ok(predicates),
257 // If we encounter a fixup error, it means that some type
258 // variable wound up unconstrained. I actually don't know
259 // if this can happen, and I certainly don't expect it to
260 // happen often, but if it did happen it probably
261 // represents a legitimate failure due to some kind of
262 // unconstrained variable.
264 // @lcnr: Let's still ICE here for now. I want a test case
268 "inference variables in normalized parameter environment: {}",
276 // FIXME: this is gonna need to be removed ...
277 /// Normalizes the parameter environment, reporting errors if they occur.
278 #[instrument(level = "debug", skip(tcx))]
279 pub fn normalize_param_env_or_error<'tcx>(
281 unnormalized_env: ty::ParamEnv<'tcx>,
282 cause: ObligationCause<'tcx>,
283 ) -> ty::ParamEnv<'tcx> {
284 // I'm not wild about reporting errors here; I'd prefer to
285 // have the errors get reported at a defined place (e.g.,
286 // during typeck). Instead I have all parameter
287 // environments, in effect, going through this function
288 // and hence potentially reporting errors. This ensures of
289 // course that we never forget to normalize (the
290 // alternative seemed like it would involve a lot of
291 // manual invocations of this fn -- and then we'd have to
292 // deal with the errors at each of those sites).
294 // In any case, in practice, typeck constructs all the
295 // parameter environments once for every fn as it goes,
296 // and errors will get reported then; so outside of type inference we
297 // can be sure that no errors should occur.
298 let mut predicates: Vec<_> =
299 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
300 .map(|obligation| obligation.predicate)
303 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
305 let elaborated_env = ty::ParamEnv::new(
306 tcx.intern_predicates(&predicates),
307 unnormalized_env.reveal(),
308 unnormalized_env.constness(),
311 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
312 // normalization expects its param-env to be already normalized, which means we have
315 // The way we handle this is by normalizing the param-env inside an unnormalized version
316 // of the param-env, which means that if the param-env contains unnormalized projections,
317 // we'll have some normalization failures. This is unfortunate.
319 // Lazy normalization would basically handle this by treating just the
320 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
322 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
323 // types, so to make the situation less bad, we normalize all the predicates *but*
324 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
325 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
327 // This works fairly well because trait matching does not actually care about param-env
328 // TypeOutlives predicates - these are normally used by regionck.
329 let outlives_predicates: Vec<_> = predicates
330 .drain_filter(|predicate| {
331 matches!(predicate.kind().skip_binder(), ty::PredicateKind::TypeOutlives(..))
336 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
337 predicates, outlives_predicates
339 let Ok(non_outlives_predicates) = do_normalize_predicates(
345 // An unnormalized env is better than nothing.
346 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
347 return elaborated_env;
350 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
352 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
353 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
354 // predicates here anyway. Keeping them here anyway because it seems safer.
355 let outlives_env: Vec<_> =
356 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
357 let outlives_env = ty::ParamEnv::new(
358 tcx.intern_predicates(&outlives_env),
359 unnormalized_env.reveal(),
360 unnormalized_env.constness(),
362 let Ok(outlives_predicates) = do_normalize_predicates(
368 // An unnormalized env is better than nothing.
369 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
370 return elaborated_env;
372 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
374 let mut predicates = non_outlives_predicates;
375 predicates.extend(outlives_predicates);
376 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
378 tcx.intern_predicates(&predicates),
379 unnormalized_env.reveal(),
380 unnormalized_env.constness(),
384 /// Normalize a type and process all resulting obligations, returning any errors
385 pub fn fully_normalize<'a, 'tcx, T>(
386 infcx: &InferCtxt<'a, 'tcx>,
387 cause: ObligationCause<'tcx>,
388 param_env: ty::ParamEnv<'tcx>,
390 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
392 T: TypeFoldable<'tcx>,
394 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
395 let selcx = &mut SelectionContext::new(infcx);
396 let Normalized { value: normalized_value, obligations } =
397 project::normalize(selcx, param_env, cause, value);
399 "fully_normalize: normalized_value={:?} obligations={:?}",
400 normalized_value, obligations
403 let mut fulfill_cx = FulfillmentContext::new();
404 for obligation in obligations {
405 fulfill_cx.register_predicate_obligation(infcx, obligation);
408 debug!("fully_normalize: select_all_or_error start");
409 let errors = fulfill_cx.select_all_or_error(infcx);
410 if !errors.is_empty() {
413 debug!("fully_normalize: select_all_or_error complete");
414 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
415 debug!("fully_normalize: resolved_value={:?}", resolved_value);
419 /// Process an obligation (and any nested obligations that come from it) to
420 /// completion, returning any errors
421 pub fn fully_solve_obligation<'a, 'tcx>(
422 infcx: &InferCtxt<'a, 'tcx>,
423 obligation: PredicateObligation<'tcx>,
424 ) -> Vec<FulfillmentError<'tcx>> {
425 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
426 engine.register_predicate_obligation(infcx, obligation);
427 engine.select_all_or_error(infcx)
430 /// Process a set of obligations (and any nested obligations that come from them)
432 pub fn fully_solve_obligations<'a, 'tcx>(
433 infcx: &InferCtxt<'a, 'tcx>,
434 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
435 ) -> Vec<FulfillmentError<'tcx>> {
436 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
437 engine.register_predicate_obligations(infcx, obligations);
438 engine.select_all_or_error(infcx)
441 /// Process a bound (and any nested obligations that come from it) to completion.
442 /// This is a convenience function for traits that have no generic arguments, such
443 /// as auto traits, and builtin traits like Copy or Sized.
444 pub fn fully_solve_bound<'a, 'tcx>(
445 infcx: &InferCtxt<'a, 'tcx>,
446 cause: ObligationCause<'tcx>,
447 param_env: ty::ParamEnv<'tcx>,
450 ) -> Vec<FulfillmentError<'tcx>> {
451 let mut engine = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
452 engine.register_bound(infcx, param_env, ty, bound, cause);
453 engine.select_all_or_error(infcx)
456 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
457 /// returns true, then either normalize encountered an error or one of the predicates did not
458 /// hold. Used when creating vtables to check for unsatisfiable methods.
459 pub fn impossible_predicates<'tcx>(
461 predicates: Vec<ty::Predicate<'tcx>>,
463 debug!("impossible_predicates(predicates={:?})", predicates);
465 let result = tcx.infer_ctxt().enter(|infcx| {
466 // HACK: Set tainted by errors to gracefully exit in case of overflow.
467 infcx.set_tainted_by_errors();
469 let param_env = ty::ParamEnv::reveal_all();
470 let ocx = ObligationCtxt::new(&infcx);
471 let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);
472 for predicate in predicates {
473 let obligation = Obligation::new(ObligationCause::dummy(), param_env, predicate);
474 ocx.register_obligation(obligation);
476 let errors = ocx.select_all_or_error();
478 // Clean up after ourselves
479 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
483 debug!("impossible_predicates = {:?}", result);
487 fn subst_and_check_impossible_predicates<'tcx>(
489 key: (DefId, SubstsRef<'tcx>),
491 debug!("subst_and_check_impossible_predicates(key={:?})", key);
493 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
495 // Specifically check trait fulfillment to avoid an error when trying to resolve
497 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
498 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
499 predicates.push(ty::Binder::dummy(trait_ref).to_poly_trait_predicate().to_predicate(tcx));
502 predicates.retain(|predicate| !predicate.needs_subst());
503 let result = impossible_predicates(tcx, predicates);
505 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
509 /// Checks whether a trait's method is impossible to call on a given impl.
511 /// This only considers predicates that reference the impl's generics, and not
512 /// those that reference the method's generics.
513 fn is_impossible_method<'tcx>(
515 (impl_def_id, trait_item_def_id): (DefId, DefId),
517 struct ReferencesOnlyParentGenerics<'tcx> {
519 generics: &'tcx ty::Generics,
520 trait_item_def_id: DefId,
522 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
524 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
525 // If this is a parameter from the trait item's own generics, then bail
526 if let ty::Param(param) = t.kind()
527 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
528 && self.tcx.parent(param_def_id) == self.trait_item_def_id
530 return ControlFlow::BREAK;
532 t.super_visit_with(self)
534 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
535 if let ty::ReEarlyBound(param) = r.kind()
536 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
537 && self.tcx.parent(param_def_id) == self.trait_item_def_id
539 return ControlFlow::BREAK;
541 r.super_visit_with(self)
543 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
544 if let ty::ConstKind::Param(param) = ct.kind()
545 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
546 && self.tcx.parent(param_def_id) == self.trait_item_def_id
548 return ControlFlow::BREAK;
550 ct.super_visit_with(self)
554 let generics = tcx.generics_of(trait_item_def_id);
555 let predicates = tcx.predicates_of(trait_item_def_id);
557 tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
558 let param_env = tcx.param_env(impl_def_id);
560 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
561 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
562 if pred.visit_with(&mut visitor).is_continue() {
563 Some(Obligation::new(
564 ObligationCause::dummy_with_span(*span),
566 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
573 tcx.infer_ctxt().ignoring_regions().enter(|ref infcx| {
574 let mut fulfill_ctxt = <dyn TraitEngine<'_>>::new(tcx);
575 fulfill_ctxt.register_predicate_obligations(infcx, predicates_for_trait);
576 !fulfill_ctxt.select_all_or_error(infcx).is_empty()
580 #[derive(Clone, Debug)]
581 enum VtblSegment<'tcx> {
583 TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
586 /// Prepare the segments for a vtable
587 fn prepare_vtable_segments<'tcx, T>(
589 trait_ref: ty::PolyTraitRef<'tcx>,
590 mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
592 // The following constraints holds for the final arrangement.
593 // 1. The whole virtual table of the first direct super trait is included as the
594 // the prefix. If this trait doesn't have any super traits, then this step
595 // consists of the dsa metadata.
596 // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
597 // other super traits except those already included as part of the first
598 // direct super trait virtual table.
599 // 3. finally, the own methods of this trait.
601 // This has the advantage that trait upcasting to the first direct super trait on each level
602 // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
603 // while not using too much extra memory.
605 // For a single inheritance relationship like this,
606 // D --> C --> B --> A
607 // The resulting vtable will consists of these segments:
610 // For a multiple inheritance relationship like this,
613 // The resulting vtable will consists of these segments:
614 // DSA, A, B, B-vptr, C, D
616 // For a diamond inheritance relationship like this,
619 // The resulting vtable will consists of these segments:
620 // DSA, A, B, C, C-vptr, D
622 // For a more complex inheritance relationship like this:
623 // O --> G --> C --> A
631 // The resulting vtable will consists of these segments:
632 // DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
633 // H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
636 // emit dsa segment first.
637 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
641 let mut emit_vptr_on_new_entry = false;
642 let mut visited = util::PredicateSet::new(tcx);
643 let predicate = trait_ref.without_const().to_predicate(tcx);
644 let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
645 smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
646 visited.insert(predicate);
648 // the main traversal loop:
649 // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
650 // that each node is emitted after all its descendents have been emitted.
651 // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
652 // this is done on the fly.
653 // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
654 // stops after it finds a node that has a next-sibling node.
655 // This next-sibling node will used as the starting point of next slice.
658 // For a diamond inheritance relationship like this,
659 // D#1 --> B#0 --> A#0
662 // Starting point 0 stack [D]
663 // Loop run #0: Stack after diving in is [D B A], A is "childless"
664 // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
665 // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
666 // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
667 // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
668 // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
669 // Loop run #1: Stack after exiting out is []. Now the function exits.
672 // dive deeper into the stack, recording the path
674 if let Some((inner_most_trait_ref, _, _)) = stack.last() {
675 let inner_most_trait_ref = *inner_most_trait_ref;
676 let mut direct_super_traits_iter = tcx
677 .super_predicates_of(inner_most_trait_ref.def_id())
680 .filter_map(move |(pred, _)| {
681 pred.subst_supertrait(tcx, &inner_most_trait_ref).to_opt_poly_trait_pred()
684 'diving_in_skip_visited_traits: loop {
685 if let Some(next_super_trait) = direct_super_traits_iter.next() {
686 if visited.insert(next_super_trait.to_predicate(tcx)) {
687 // We're throwing away potential constness of super traits here.
688 // FIXME: handle ~const super traits
689 let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
692 emit_vptr_on_new_entry,
693 Some(direct_super_traits_iter),
695 break 'diving_in_skip_visited_traits;
697 continue 'diving_in_skip_visited_traits;
706 // Other than the left-most path, vptr should be emitted for each trait.
707 emit_vptr_on_new_entry = true;
709 // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
711 if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
712 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
713 trait_ref: *inner_most_trait_ref,
714 emit_vptr: *emit_vptr,
719 'exiting_out_skip_visited_traits: loop {
720 if let Some(siblings) = siblings_opt {
721 if let Some(next_inner_most_trait_ref) = siblings.next() {
722 if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
723 // We're throwing away potential constness of super traits here.
724 // FIXME: handle ~const super traits
725 let next_inner_most_trait_ref =
726 next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
727 *inner_most_trait_ref = next_inner_most_trait_ref;
728 *emit_vptr = emit_vptr_on_new_entry;
731 continue 'exiting_out_skip_visited_traits;
736 continue 'exiting_out;
745 fn dump_vtable_entries<'tcx>(
748 trait_ref: ty::PolyTraitRef<'tcx>,
749 entries: &[VtblEntry<'tcx>],
751 let msg = format!("vtable entries for `{}`: {:#?}", trait_ref, entries);
752 tcx.sess.struct_span_err(sp, &msg).emit();
755 fn own_existential_vtable_entries<'tcx>(
757 trait_ref: ty::PolyExistentialTraitRef<'tcx>,
759 let trait_methods = tcx
760 .associated_items(trait_ref.def_id())
761 .in_definition_order()
762 .filter(|item| item.kind == ty::AssocKind::Fn);
763 // Now list each method's DefId (for within its trait).
764 let own_entries = trait_methods.filter_map(move |trait_method| {
765 debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
766 let def_id = trait_method.def_id;
768 // Some methods cannot be called on an object; skip those.
769 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
770 debug!("own_existential_vtable_entry: not vtable safe");
777 tcx.arena.alloc_from_iter(own_entries.into_iter())
780 /// Given a trait `trait_ref`, iterates the vtable entries
781 /// that come from `trait_ref`, including its supertraits.
782 fn vtable_entries<'tcx>(
784 trait_ref: ty::PolyTraitRef<'tcx>,
785 ) -> &'tcx [VtblEntry<'tcx>] {
786 debug!("vtable_entries({:?})", trait_ref);
788 let mut entries = vec![];
790 let vtable_segment_callback = |segment| -> ControlFlow<()> {
792 VtblSegment::MetadataDSA => {
793 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
795 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
796 let existential_trait_ref = trait_ref
797 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
799 // Lookup the shape of vtable for the trait.
800 let own_existential_entries =
801 tcx.own_existential_vtable_entries(existential_trait_ref);
803 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
804 debug!("vtable_entries: trait_method={:?}", def_id);
806 // The method may have some early-bound lifetimes; add regions for those.
807 let substs = trait_ref.map_bound(|trait_ref| {
808 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
809 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
810 GenericParamDefKind::Type { .. }
811 | GenericParamDefKind::Const { .. } => {
812 trait_ref.substs[param.index as usize]
817 // The trait type may have higher-ranked lifetimes in it;
818 // erase them if they appear, so that we get the type
819 // at some particular call site.
821 .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
823 // It's possible that the method relies on where-clauses that
824 // do not hold for this particular set of type parameters.
825 // Note that this method could then never be called, so we
826 // do not want to try and codegen it, in that case (see #23435).
827 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
828 if impossible_predicates(tcx, predicates.predicates) {
829 debug!("vtable_entries: predicates do not hold");
830 return VtblEntry::Vacant;
833 let instance = ty::Instance::resolve_for_vtable(
835 ty::ParamEnv::reveal_all(),
839 .expect("resolution failed during building vtable representation");
840 VtblEntry::Method(instance)
843 entries.extend(own_entries);
846 entries.push(VtblEntry::TraitVPtr(trait_ref));
851 ControlFlow::Continue(())
854 let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
856 if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
857 let sp = tcx.def_span(trait_ref.def_id());
858 dump_vtable_entries(tcx, sp, trait_ref, &entries);
861 tcx.arena.alloc_from_iter(entries.into_iter())
864 /// Find slot base for trait methods within vtable entries of another trait
865 fn vtable_trait_first_method_offset<'tcx>(
868 ty::PolyTraitRef<'tcx>, // trait_to_be_found
869 ty::PolyTraitRef<'tcx>, // trait_owning_vtable
872 let (trait_to_be_found, trait_owning_vtable) = key;
875 let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
877 let vtable_segment_callback = {
878 let mut vtable_base = 0;
882 VtblSegment::MetadataDSA => {
883 vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
885 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
886 if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
887 return ControlFlow::Break(vtable_base);
889 vtable_base += util::count_own_vtable_entries(tcx, trait_ref);
895 ControlFlow::Continue(())
899 if let Some(vtable_base) =
900 prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
904 bug!("Failed to find info for expected trait in vtable");
908 /// Find slot offset for trait vptr within vtable entries of another trait
909 pub fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
912 Ty<'tcx>, // trait object type whose trait owning vtable
913 Ty<'tcx>, // trait object for supertrait
916 let (source, target) = key;
917 assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.needs_infer());
918 assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.needs_infer());
920 // this has been typecked-before, so diagnostics is not really needed.
921 let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
923 let trait_ref = ty::TraitRef {
924 def_id: unsize_trait_did,
925 substs: tcx.mk_substs_trait(source, &[target.into()]),
927 let obligation = Obligation::new(
928 ObligationCause::dummy(),
929 ty::ParamEnv::reveal_all(),
930 ty::Binder::dummy(ty::TraitPredicate {
932 constness: ty::BoundConstness::NotConst,
933 polarity: ty::ImplPolarity::Positive,
937 let implsrc = tcx.infer_ctxt().enter(|infcx| {
938 let mut selcx = SelectionContext::new(&infcx);
939 selcx.select(&obligation).unwrap()
942 let Some(ImplSource::TraitUpcasting(implsrc_traitcasting)) = implsrc else {
946 implsrc_traitcasting.vtable_vptr_slot
949 pub fn provide(providers: &mut ty::query::Providers) {
950 object_safety::provide(providers);
951 structural_match::provide(providers);
952 *providers = ty::query::Providers {
953 specialization_graph_of: specialize::specialization_graph_provider,
954 specializes: specialize::specializes,
955 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
956 own_existential_vtable_entries,
958 vtable_trait_upcasting_coercion_new_vptr_slot,
959 subst_and_check_impossible_predicates,
960 is_impossible_method,
961 try_unify_abstract_consts: |tcx, param_env_and| {
962 let (param_env, (a, b)) = param_env_and.into_parts();
963 const_evaluatable::try_unify_abstract_consts(tcx, (a, b), param_env)